When initialize an entity framework context.
One is to initialize at class level, such as
public class EntityContactManagerRepository
: ContactManager.Models.IContactManagerRepository
{
private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
// Contact methods
public Contact GetContact(int id)
{
return (from c in _entities.ContactSet.Include("Group")
where c.Id == id
select c).FirstOrDefault();
}
}
The other way is to initialize at the method level.
public class EntityContactManagerRepository
: ContactManager.Models.IContactManagerRepository
{
// Contact methods
public Contact GetContact(int id)
{
using (var entities = new ContactManagerDBEntities())
return (from c in entities.ContactSet.Include("Group")
where c.Id == id
select c).FirstOrDefault();
}
}
From an Ado.Net background, I prefer the later one-initialize in method, but the first one is from the example developed by Stephen Walthe. Or another question, does it matter at all?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…