如何在EF4.0实现中配置ObjectContext?

时间:2011-06-16 15:09:14

标签: c# entity-framework-4

我有以下代码结构。它是一个WPF应用程序,DAL通过WCF服务公开。我们已经创建了我们的域实体,我们在从EF实体填充后传递它们。

EDMX生成的代码: -

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();
    }
}

现在为了实例化ObjectContext,我们创建了一个BaseDAL,应用程序中的每个DAL都继承自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>
    public BaseDal()
    {

        string connstring = ConfigurationManager.ConnectionStrings["EDiscDbConnection"].ConnectionString;
        //Decrypt Connection String
        context = new EDiscDbConnection(Encryption.GetDecryptedString(connstring, "F045FBC3A427A1018E297BF442216C3FB3D62F51B57A33AC744B6238E05ADB08"));
        //context = new EDiscDbConnection();

    }
}

DAL如下: -

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;
    }
}

我对此实施有以下问题

  1. 我们没有处理EDiscDbConnection。这是内存泄漏吗?
  2. 在GetAllFacilities()方法中实现using()会自动处理EDiscDbConnection还是我必须在BaseDAL中实现IDisposable?
  3. 我很少收到错误“已经是一个与此命令关联的开放DataReader,必须先关闭”。这可能与不处理EDiscDbConnection有关。
  4. 在这些情况下,人们遵循的最佳做法是什么?请建议。

1 个答案:

答案 0 :(得分:0)

参考这个问题:Entity Framework and Connection Pooling

简而言之,您应该将查询包装在using()语句中,以确保在每次执行查询后对它们进行垃圾回收。