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 Interfaceirepository:idisposable {
Gets the Iquerable interface query for a table IQueryable<T> all<t> ()whereR |class;
Insert a recordvoidInsert<t> (T entity)whereT:class;
According to the conditions, get a record T get<T> (Expression<func<t,BOOL>> conditions)whereT:class;
Pass in a previously obtained T object, modify the recordvoidUpdate<t> (T entity)whereT:class;
Delete a recordvoidDelete<t> (T entity)whereT:class;
Save all changesintSaveChanges (); }
Then the realization of Repository.cs
Public classRepository:irepository { PrivateDbContext context; PublicRepository (DbContext DbContext) {context=DbContext; } PublicIqueryable<t> all<t> ()whereT:class { returnContext. Set<t>(). Asnotracking (); } Public voidInsert<t> (T entity)whereT:class{context. Set<T>(). ADD (entity); } PublicT get<t> (Expression<func<t,BOOL>> conditions)whereT:class { returnAll<t>(). FirstOrDefault (conditions); } Public voidUpdate<t> (T entity)whereT:class { varEntry =context. Entry (entity); if(Entry. state = =entitystate.detached) {context. Set<T>(). Attach (entity); } entry. State=entitystate.modified; } Public voidDelete<t> (T entity)whereT:class { varEntry =context. Entry (entity); if(Entry. state = =entitystate.detached) {context. Set<T>(). Attach (entity); } entry. State=entitystate.deleted; } Public intSaveChanges () {returncontext. SaveChanges (); } Public voidDispose () {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, specific application Public Static irepository Create () { returnnew Repository (new dbfactory (). DbContext); } }
At the business logic level, we can
using (var db = dbfactory.create ()) { // This can be the code to be deleted or changed,// 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