0

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.

2
  • 3
    Looks like you are trying to recreate the repository pattern Commented Nov 23, 2019 at 16:31
  • looking into that now, thanks for the suggestion. Commented Nov 25, 2019 at 13:43

1 Answer 1

1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.