Skip to content

Commit 4f19b77

Browse files
951423: Added Entity Framework sample in core platform
1 parent e7f4b0f commit 4f19b77

File tree

164 files changed

+166746
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

164 files changed

+166746
-0
lines changed
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using System.Collections.Generic;
3+
using System.ComponentModel.DataAnnotations;
4+
using System.Data;
5+
using Syncfusion.EJ2.Base;
6+
using Microsoft.EntityFrameworkCore;
7+
using Microsoft.EntityFrameworkCore.Metadata.Internal;
8+
9+
namespace Grid_EF.Controllers
10+
{
11+
[ApiController]
12+
public class GridController : ControllerBase
13+
{
14+
string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NithyaSivaprakasam\Downloads\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30";
15+
16+
/// <summary>
17+
/// Processes the DataManager request to perform searching, filtering, sorting, and paging operations.
18+
/// </summary>
19+
/// <param name="DataManagerRequest">Contains the details of the data operation requested.</param>
20+
/// <returns>Returns a JSON object along with the total record count.</returns>
21+
[HttpPost]
22+
[Route("api/[controller]")]
23+
public object Post([FromBody] DataManagerRequest DataManagerRequest)
24+
{
25+
// Retrieve data from the data source (e.g., database).
26+
IQueryable<Orders> DataSource = GetOrderData().AsQueryable();
27+
28+
// Initialize QueryableOperation instance.
29+
QueryableOperation queryableOperation = new QueryableOperation();
30+
31+
// Handling searching operation.
32+
if (DataManagerRequest.Search != null && DataManagerRequest.Search.Count > 0)
33+
{
34+
DataSource = queryableOperation.PerformSearching(DataSource, DataManagerRequest.Search);
35+
//Add custom logic here if needed and remove above method.
36+
}
37+
// Handling filtering operation.
38+
if (DataManagerRequest.Where != null && DataManagerRequest.Where.Count > 0)
39+
{
40+
foreach (WhereFilter condition in DataManagerRequest.Where)
41+
{
42+
foreach (WhereFilter predicate in condition.predicates)
43+
{
44+
DataSource = queryableOperation.PerformFiltering(DataSource, DataManagerRequest.Where, predicate.Operator);
45+
//Add custom logic here if needed and remove above method.
46+
}
47+
}
48+
}
49+
50+
// Handling sorting operation.
51+
if (DataManagerRequest.Sorted != null && DataManagerRequest.Sorted.Count > 0)
52+
{
53+
DataSource = queryableOperation.PerformSorting(DataSource, DataManagerRequest.Sorted);
54+
//Add custom logic here if needed and remove above method.
55+
}
56+
57+
// Get the total count of records.
58+
int totalRecordsCount = DataSource.Count();
59+
60+
// Handling paging operation.
61+
if (DataManagerRequest.Skip != 0)
62+
{
63+
DataSource = queryableOperation.PerformSkip(DataSource, DataManagerRequest.Skip);
64+
//Add custom logic here if needed and remove above method.
65+
}
66+
if (DataManagerRequest.Take != 0)
67+
{
68+
DataSource = queryableOperation.PerformTake(DataSource, DataManagerRequest.Take);
69+
//Add custom logic here if needed and remove above method.
70+
}
71+
72+
// Return data based on the request.
73+
return new { result = DataSource, count = totalRecordsCount };
74+
}
75+
76+
/// <summary>
77+
/// Retrieves the order data from the database.
78+
/// </summary>
79+
/// <returns>Returns a list of orders fetched from the database.</returns>
80+
[HttpGet]
81+
[Route("api/[controller]")]
82+
public List<Orders> GetOrderData()
83+
{
84+
using (OrderDbContext Context = new OrderDbContext(ConnectionString))
85+
{
86+
// Retrieve orders from the orders DbSet and convert to list asynchronously.
87+
List<Orders> orders = Context.Orders.ToList();
88+
return orders;
89+
}
90+
}
91+
92+
// Create a class that inherits from DbContext(Entity Framework Core).
93+
public class OrderDbContext : DbContext
94+
{
95+
//Declare a private variable to store the connection string.
96+
private readonly string _ConnectionString;
97+
98+
//Define a constructor that accepts a connection string.
99+
public OrderDbContext(string ConnectionString)
100+
{
101+
//Store the provided connection string.
102+
_ConnectionString = ConnectionString;
103+
}
104+
105+
//Override the onConfiguring method to tell EF Core to use SQL server.
106+
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
107+
{
108+
// Use the connection string to configure the database connection.
109+
optionsBuilder.UseSqlServer(_ConnectionString);
110+
}
111+
112+
// Define a DbSet to represent the orders table in the database.
113+
public DbSet<Orders> Orders { get; set; }
114+
}
115+
116+
/// <summary>
117+
/// Inserts a new data item into the data collection.
118+
/// </summary>
119+
/// <param name="value">It contains the new record detail which is need to be inserted.</param>
120+
/// <returns>Returns void.</returns>
121+
[HttpPost]
122+
[Route("api/[controller]/Insert")]
123+
public void Insert([FromBody] CRUDModel<Orders> value)
124+
{
125+
using (OrderDbContext Context = new OrderDbContext(ConnectionString))
126+
{
127+
// Add the provided order to the orders DbSet.
128+
Context.Orders.Add(value.value);
129+
130+
// Save changes to the database.
131+
Context.SaveChanges();
132+
}
133+
134+
//Add custom logic here if needed and remove above method.
135+
}
136+
137+
/// <summary>
138+
/// Update a existing data item from the data collection.
139+
/// </summary>
140+
/// <param name="value">It contains the updated record detail which is need to be updated.</param>
141+
/// <returns>Returns void.</returns>
142+
[HttpPost]
143+
[Route("api/[controller]/Update")]
144+
public void Update([FromBody] CRUDModel<Orders> value)
145+
{
146+
using (OrderDbContext Context = new OrderDbContext(ConnectionString))
147+
{
148+
Orders existingOrder = Context.Orders.Find(value.value.OrderID);
149+
if (existingOrder != null)
150+
{
151+
// Update the existing order with the new values.
152+
Context.Entry(existingOrder).CurrentValues.SetValues(value.value);
153+
154+
// Save changes to the database.
155+
Context.SaveChanges();
156+
}
157+
}
158+
159+
//Add custom logic here if needed and remove above method.
160+
}
161+
162+
/// <summary>
163+
/// Remove a specific data item from the data collection.
164+
/// </summary>
165+
/// <param name="value">It contains the specific record detail which is need to be removed.</param>
166+
/// <return>Returns void.</return>
167+
[HttpPost]
168+
[Route("api/[controller]/Remove")]
169+
public void Remove([FromBody] CRUDModel<Orders> value)
170+
{
171+
int OrderId = Convert.ToInt32(value.key.ToString());
172+
using (OrderDbContext Context = new OrderDbContext(ConnectionString))
173+
{
174+
Orders Order = Context.Orders.Find(OrderId);
175+
if (Order != null)
176+
{
177+
// Remove the order from the orders DbSet.
178+
Context.Orders.Remove(Order);
179+
180+
// Save changes to the database.
181+
Context.SaveChanges();
182+
}
183+
}
184+
185+
//Add custom logic here if needed and remove above method.
186+
}
187+
188+
/// <summary>
189+
/// Batch update (Insert, Update, and Delete) a collection of data items from the data collection.
190+
/// </summary>
191+
/// <param name="value">The set of information along with details about the CRUD actions to be executed from the database.</param>
192+
/// <returns>Returns void.</returns>
193+
[HttpPost]
194+
[Route("api/[controller]/BatchUpdate")]
195+
public IActionResult BatchUpdate([FromBody] CRUDModel<Orders> value)
196+
{
197+
using (OrderDbContext Context = new OrderDbContext(ConnectionString))
198+
{
199+
if (value.changed != null && value.changed.Count > 0)
200+
{
201+
foreach (Orders Record in (IEnumerable<Orders>)value.changed)
202+
{
203+
// Update the changed records.
204+
Context.Orders.UpdateRange(Record);
205+
}
206+
}
207+
208+
if (value.added != null && value.added.Count > 0)
209+
{
210+
foreach (Orders Record in (IEnumerable<Orders>)value.added)
211+
{
212+
foreach (Orders order in value.added)
213+
{
214+
// This ensures EF does not try to insert OrderID.
215+
order.OrderID = default;
216+
}
217+
// Add new records.
218+
Context.Orders.AddRange(value.added);
219+
}
220+
}
221+
222+
if (value.deleted != null && value.deleted.Count > 0)
223+
{
224+
foreach (Orders Record in (IEnumerable<Orders>)value.deleted)
225+
{
226+
// Find and delete the records.
227+
Orders ExistingOrder = Context.Orders.Find(Record.OrderID);
228+
if (ExistingOrder != null)
229+
{
230+
Context.Orders.Remove(ExistingOrder);
231+
}
232+
}
233+
}
234+
235+
// Save changes to the database.
236+
Context.SaveChanges();
237+
}
238+
return new JsonResult(value);
239+
}
240+
241+
242+
public class CRUDModel<T> where T : class
243+
{
244+
public string? action { get; set; }
245+
public string? keyColumn { get; set; }
246+
public object? key { get; set; }
247+
public T? value { get; set; }
248+
public List<T>? added { get; set; }
249+
public List<T>? changed { get; set; }
250+
public List<T>? deleted { get; set; }
251+
public IDictionary<string, object>? @params { get; set; }
252+
}
253+
254+
public class Orders
255+
{
256+
[Key]
257+
public int? OrderID { get; set; }
258+
public string? CustomerID { get; set; }
259+
public int? EmployeeID { get; set; }
260+
public decimal Freight { get; set; }
261+
public string? ShipCity { get; set; }
262+
}
263+
}
264+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.3" />
11+
<PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="29.1.35" />
12+
</ItemGroup>
13+
</Project>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<ActiveDebugProfile>https</ActiveDebugProfile>
5+
</PropertyGroup>
6+
</Project>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.12.35527.113
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grid_EntityFrameWork", "Grid_EntityFrameWork.csproj", "{D56A855D-3C13-48FB-9AF4-86590FD014E7}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{D56A855D-3C13-48FB-9AF4-86590FD014E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{D56A855D-3C13-48FB-9AF4-86590FD014E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{D56A855D-3C13-48FB-9AF4-86590FD014E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{D56A855D-3C13-48FB-9AF4-86590FD014E7}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
EndGlobal
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
@page
2+
@model ErrorModel
3+
@{
4+
ViewData["Title"] = "Error";
5+
}
6+
7+
<h1 class="text-danger">Error.</h1>
8+
<h2 class="text-danger">An error occurred while processing your request.</h2>
9+
10+
@if (Model.ShowRequestId)
11+
{
12+
<p>
13+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
14+
</p>
15+
}
16+
17+
<h3>Development Mode</h3>
18+
<p>
19+
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
20+
</p>
21+
<p>
22+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
23+
It can result in displaying sensitive information from exceptions to end users.
24+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
25+
and restarting the app.
26+
</p>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System.Diagnostics;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.AspNetCore.Mvc.RazorPages;
4+
5+
namespace Grid_EF.Pages
6+
{
7+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
8+
[IgnoreAntiforgeryToken]
9+
public class ErrorModel : PageModel
10+
{
11+
public string? RequestId { get; set; }
12+
13+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
14+
15+
private readonly ILogger<ErrorModel> _logger;
16+
17+
public ErrorModel(ILogger<ErrorModel> logger)
18+
{
19+
_logger = logger;
20+
}
21+
22+
public void OnGet()
23+
{
24+
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
25+
}
26+
}
27+
28+
}

0 commit comments

Comments
 (0)