Reputation: 693
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.
Upvotes: 0
Views: 113
Reputation: 4246
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;
}
Upvotes: 1