The code of this access layer is actually a senior in the garden, I just feel so, recorded down.
This access layer requires the installation of EntityFramework Core through NuGet, but the individual believes that EF 6 is also available.
collocation database, preferably SQL Server (Microsoft Support, you understand)
Paste the following code
First IRepository.cs.
Public interface irepository:idisposable {
Gets a table of iquerable interface queries iqueryable<t> all<t> () where t:class;
Insert a record void insert<t> (T entity) where T:class;
According to the conditions, obtain a record T get<t> (expression<func<t, bool>> conditions) where t:class;
Pass in a previously obtained T object, modify the record void update<t> (t entity) where T:class;
Delete a record void delete<t> (T entity) where T:class;
Save all Changes int SaveChanges (); }
Then the realization of Repository.cs
public class Repository:irepository {private DbContext context; Public Repository (DbContext DbContext) {context = DbContext; } public iqueryable<t> all<t> () where T:class {return context. Set<t> (). Asnotracking (); The public void insert<t> (T entity) where T:class {context. Set<t> (). ADD (entity); } public T get<t> (expression<func<t, bool>> conditions) where T:class {retur n all<t> (). FirstOrDefault (conditions); The public void update<t> (T entity) where T:class {var entry = context. Entry (entity); if (entry. state = = entitystate.detached) {context. Set<t> (). Attach (entity); } entry. state = entitystate.modified; } public void delete<t> (T entity) where T:class { var entry = context. Entry (entity); if (entry. state = = entitystate.detached) {context. Set<t> (). Attach (entity); } entry. state = entitystate.deleted; } public int SaveChanges () {return context. SaveChanges (); public void Dispose () {context. Dispose (); } }
Specific use:
You can write a dbfactory method that is used to generate a database connection (object)
public class Dbfactory { //There may be a database connection string or something, the specific application of public static IRepository Create () { return New Repository (New Dbfactory (). DbContext); } }
At the business logic level, we can
using (var db = Dbfactory.create ()) {/ /here can be additions and deletions of code, // db, for example. Insert<user> (User); Db. Insert<userother> (UO);
can be arbitrarily cross-table, EntityFramework own transactions, and finally savechanges will be processed together
int result = db. SaveChanges (); SaveChanges () Returns a change number, so you can view the result with a number of type int. }
A simple database access layer based on EntityFramework core for lightweight database services