A simple database access layer based on EntityFramework Core, applicable to lightweight database services and lightweight Databases
The code of this access layer is actually from a senior in the garden. I just thought it was good and recorded it.
The access layer needs to install EntityFramework Core through Nuget, but I personally think EF 6 can also be used.
It is best to match databases with SQL Server (supported by Microsoft, you know)
Post Code below
First, IRepository. cs
Public interface IRepository: IDisposable {
// Obtain the IQuerable interface of a table to query IQueryable <T> All <T> () where T: class;
// Insert a record void Insert <T> (T entity) where T: class;
// Obtain a record T Get <T> (Expression <Func <T, bool> conditions) where T: class according to the condition;
// Input 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 to int SaveChanges ();}
Then implement 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(); } 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 { return All<T>().FirstOrDefault(conditions); } 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 to generate a database connection (object)
Public class DbFactory {// there may be a database connection string or something here. The specific application is public static IRepository Create () {return new Repository (new DbFactory (). DbContext );}}
At the business logic layer, we can
Using (var db = DbFactory. create () {// here can be the code for addition, deletion, and modification, // such as db. insert <User> (user); db. insert <UserOther> (uo );
// Any cross-table operation is supported. The EntityFramework comes with the transaction, and the SaveChanges will process the transaction together.
Int result = db. SaveChanges (); // SaveChanges () returns a change number, so you can use an int type number to view the result. }