How to dispose ObjectContext in EF4.0 implementation?
I have the following code structure. It is a WPF application with DAL exposed thru WCF services. we have created our domain entities and we are passing them after populating from EF entities.
EDMX Generated Code:-
public partial class EDiscDbConnection : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new EDiscDbConnection object using the connection string found in the 'EDiscDbConnection' section of the application configuration file.
/// </summary>
public EDiscDbConnection() : base("name=EDiscDbConnection", "EDiscDbConnection")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
}
Now for instantiating ObjectContext, we have created a BaseDAL and every DAL in the application inherits from BaseDal
BaseDAL:-
public class BaseDal
{
public EDiscDbConnection context; // EF Content used for connection to the Database.
/// <summary>
/// Base constructor to initilize the Entity Framework Content.
/// </summary>
开发者_Python百科 public BaseDal()
{
string connstring = ConfigurationManager.ConnectionStrings["EDiscDbConnection"].ConnectionString;
//Decrypt Connection String
context = new EDiscDbConnection(Encryption.GetDecryptedString(connstring, "F045FBC3A427A1018E297BF442216C3FB3D62F51B57A33AC744B6238E05ADB08"));
//context = new EDiscDbConnection();
}
}
DAL is as follows:-
public partial class PatientChartDal : BaseDal
{
public List<UserFacility> GetAllFacilities()
{
List<UserFacility> userFacilities = new List<UserFacility>();
IEnumerable<Facility> userFac = from fac in context.Facilities
from usrfac in fac.UserFacilityMappings
where fac.IsActive
select fac;
if (userFac != null && userFac.Count() > 0)
{
userFacilities = new List<Domain.UserFacility>();
foreach (var u in userFac.Distinct())
{
userFacilities.Add(new Domain.UserFacility()
{
Name = u.Name,
FacilityId = u.FacilityId,
//FacilityConfiguration = GetFacilityConfiguration(u.FacilityId),
//UserConfiguration = GetFacilityUserConfiguration(u.FacilityId, userId),
Code = u.Code,
//TxAreaID = u.TxAreaID,
TimeZone = ConvertToDomainEntity(u.Seed_TimeZone)
}
);
}
}
return userFacilities;
}
}
I have following questions regarding this implementation
- We are not disposing of EDiscDbConnection. Is this a memory leak ?
- Will implementing using() in GetAllFacilities() method automatically dispose EDiscDbConnection or i have to implement IDisposable in BaseDAL?
- I am very rarely getting an error "already an open DataReader associated with this Command which must be closed first ". Can this be associated with not disposing the EDiscDbConnection.
What is the best practices people are following in these cases. Please suggest.
Referring to this question: Entity Framework and Connection Pooling
In short, you should wrap your queries in a using()
statement to ensure that they are garbage collected after each query execution.
精彩评论