简体   繁体   中英

Passing entity context into class constructor

I'm still a little new to Entity Framework so I'm still working through some of the basics. I have a data access layer that's doing most of the heavy lifting. However, as I'm learning about EF and contexts I'm realizing how important it is to maintain one context especially when you're trying to update children of an instance of a entity object. So my plan is to create the context on the front end and pass it into the data layer.

Front End:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        supplyEntities ctx = new supplyEntities();
        GroupsClass gc = new GroupsClass(ctx);
     }
}

Data Layer:

public class GroupsClass
{
    private supplyEntities context;

    public GroupsClass(supplyEntities ctx)
    {
        context = ctx;
    }

    public List<group> GetAllGroups()
    {
        context.do stuff;
    }
}

It errors on "a field initializer cannot reference the non-static field, method or property". What am I missing? Or, should I be doing this a different way?

The error is strange in sense that it tells about something that happens in static method. You cannot use instance-level member when running inside a static method, that's what this error means. Can you paste the exact code in which error is reported?

And aside from the error, one piece of an advice. Do not create data context on the front end. That means that front end is irrevocably tied to the context. There is no way to mock it, there is no way to test it automatically, no way to replace it with any other implementation, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM