0

I have an EF Core data layer and i want to wrap it around an interface to separte it from the business logic. Now the issue is that i am not sure i am doing it correctly. First, i was just using static context to be alive all the time but that seems just wrong to me.

Should i create a new instance of context for each request? Then i think it would cause issue with entity tracking and changes i make will not save when SaveChanges is called. Should i even return an EF entity object or just a model object to not expose data related to the database

Tldr: i just need some direction on how to wrap my EF Core data layer correctly

0

Use the repository pattern

public class MyRepo : IMyRepo
{
    public MyRepo(string connectionString) {
        ... instantiate DB context
    }
    public MyObject GetObjectById(string id) {
        ...EF stuff goes in here
    }

    ... more methods that return business objects
}

Inject via a DI framework in your app. Use Singleton or per request context as appropriate

  • When is it appropriate to use singleton and when is it to use per request. – Aviv Biton Aug 20 '18 at 10:29
  • that depends on your application. I think in most cases you are good with a singleton when your connection string is constant – Ewan Aug 20 '18 at 11:11
  • Okay. One more question. Lets say i have a class person that represents a database table and mapped by ef core. Now if the business layer request a person object from the repo class should i return just the original object fetched by ef or create another class for example, personModel and return it instead of the person object that is mapped to the db – Aviv Biton Aug 20 '18 at 11:23
  • for complete separation, the models returned by the repo should not have any EF attributes or other references to EF dlls. – Ewan Aug 20 '18 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.