简体   繁体   中英

Separating database operations in ASP.NET Core MVC

I have an ASP.NET Core MVC application with several projects: the main project of the application (WebApp) and a database class library with models and db_context . In the database library I want to add all the operations methods, like save, update and delete.

But no matter what I try, I cannot get this to work; this is the method that I have:

MyProject.Data class library

public class DbOps
{
    public static async Task<bool> SaveCustomerChangesToDb(DbContext context, Model model, object objectToSave)
    {
       context.model.Add(objectToSave);
       await context.SaveChangesAsync();
       // some more logic...
       return true;
    }
}

That method gets called in the controller, but this just causes errors. How can I write a model-agnostic method to save changes in this class, that I can use with multiple view models and database models?

I'm using EF en Net Core 2.1. In the MyProject.WebApp project I have set references to the data class library correctly. All the migrations also went fine, for example, I can add data manually in the SQL editor in VS2019.

You can write something like this:

 public static async Task<bool> SaveCustomerChangesToDb<TEntity>(DbContext context, TEntity objectToSave) where TEntity:class
    {
       context.Set<TEntity>().Add(objectToSave);
       await context.SaveChangesAsync();
       // some more logic...
       return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM