문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top