Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
scroll top