The ADO.NET Provider for ServiceNow supports Entity Framework which requires C1.EntityFrameworkCore.ServiceNow package to be installed. This article demonstrates the model-first approach to build an Entity Framework model that maps data tables to classes for simpler access to ServiceNow.
In the following example, we used Incident.cs file to map the Incident datatable. ServiceNowContext class has been defined to access the Incident datatable and establish a connection to the ServiceNow service by overriding the OnConfiguring method. This method invokes the UseServiceNow method of DbContextOptionsBuilder class to configure the context and establish connection with ServiceNow service. To see the code for ServiceNowContext class, please refer to ServiceNowContext.cs file.
The LINQ queries can be used to perform different data operations to the mapped classes as demonstrated in the code below.
Note: For LINQ queries, the code must have declared "using System.Linq".
INSERT |
C# |
コードのコピー
|
public static void Insert(ServiceNowContext context)
{
Console.WriteLine("\nQuery Insert...");
Incident incident = new Incident
{
SysId = "581ccaf9c0a8016400b98a06818d57d8",
CallerId = "781ccaf9c0a8016400b98a06818d57d8",
Category = "inquiry",
Description = "I am unable to connect to the server. It appears to be down.",
CloseCode = "Solved (Permanently)"
};
context.Incident.Add(incident);
int result = context.SaveChanges();
Console.WriteLine("Number row insert: " + result);
}
|
|
SELECT |
C# |
コードのコピー
|
public static void Select(ServiceNowContext context)
{
Console.WriteLine("Query all Incidents...");
var records =
from p in context.Incident
select p;
foreach (var incident in records)
{
Console.WriteLine("{0} - {1} - {2} - {3} ",
incident.CallerId, incident.Category, incident.Description, incident.CloseCode);
}
}
|
|
UPDATE |
C# |
コードのコピー
|
public static void Update(ServiceNowContext context)
{
Console.WriteLine("\nQuery Update...");
var incidents = context.Incident.Where(x => x.CallerId == "781ccaf9c0a8016400b98a06818d57d8");
foreach (var incident in incidents)
{
incident.Category = "Hardware";
incident.CloseCode = "Solved Remotely (Permanently)";
}
int result = context.SaveChanges();
Console.WriteLine("Number row update: " + result);
}
|
|
DELETE |
C# |
コードのコピー
|
public static void Delete(ServiceNowContext context)
{
Console.WriteLine("\nQuery Delete...");
var products = context.Incident.Where(x => x.CallerId == "781ccaf9c0a8016400b98a06818d57d8");
foreach (var product in products)
{
context.Incident.Remove(product);
}
int result = context.SaveChanges();
Console.WriteLine("Number row delete: " + result);
}
|
|
Note: Scaffolding feature supports user to create the model and dbcontext when you create model in the Entity Framework for all dataconnectors.