Passing DbContext instance into method within a using statement

.net c# entity-framework-6

Question

I have several business objects that wrap my data models I created using Entity Framework 6. These business objects all have CRUD methods to interact with the data models.

For simplicity let's only look at the Get() function. I instantiate the context, and then I'll get the reference. The Get() function also has a parameter to determine if we should get values related to the client, ClientValues. ClientValues is also a business object that contains aforementioned CRUD operations.

So my question is, rather than creating a new instance of the context in ClientValues.Get(), should I be passing the current context reference and use that? Will this even be more efficient or is .NET smart enough to handle this? I've already tried this and it appears that context gets disposed when I pass it into another method, but I assume there is a proper way of doing this?

public class Client
{
    public int Id { get; set; }
    public List<ClientValue> ClientValues { get; set; }
    ...

    public void Get(int id, bool getValues)
    {
        using (var context = new MyDbEntities()) // MyDbEntities inherits DbContext obviously
        {
            var efClientModel = context.Clients.Where(x => x.Id == id).FirstOrDefault();
            // populate business object
            if (getValues)
            {
                foreach (var value in efClientModel.ClientValues)
                {
                    var newValue = new ClientValue();
                    newValue.Get(value.Id, context); // this is where I pass the context in
                    this.ClientValues.Add(newValue);
                }
            }

        }
    }
}

What ClientValues.Get() looks like:

 public void Get(int valueId, MyDbEntities passedContext = null)
 {
     using (var context = passedContext == null ? new MyDbEntities() : passedContext)
     {
         ...
     }
 }
1
1
5/23/2016 8:54:33 PM

Popular Answer

I would highly recommend not having your entities responsible for any database operations. But if you do choose to continue down this path, I would strongly suggest having all your Get() operations accept the DbContext as a paramter, with the context owned by whatever needs to do the Geting (with the "owner" responsible for the using).

0
5/23/2016 9:20:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow