【问题标题】:Could not loop thru data return from DAL Entity framework in PL无法循环通过 PL 中 DAL 实体框架返回的数据
【发布时间】:2012-03-04 02:44:05
【问题描述】:

我在我的项目中使用 Entity Framework 4。一项基本要求是使用存储过程从数据库中获取数据,并在表示层中循环这些数据,并与下拉列表、网格控件等绑定。

我的流程如下:

PL 调用 BLL 和 BLL 调用 DAL

示例代码:

DAL:

namespace DAL.Repository
{
    public class CountryRepository
    {
        public static IList GetCountry(string CountryId)
        { 
            using(MyDBEntities context=new MyDBEntities())
            {
               // it calls SP in DB thru EF to fetch data
                return context.GetCountry(CountryId).ToList();

            }
        }
    }
}

BLL

namespace BLL
{
   public class Country
    {
       public static IList GetCountry(string CountryId)
       {
           return DAL.Repository.CountryRepository.GetCountry(CountryId);
       }
    }
}

PL

  ddlCountry.DataTextField = "CountryName";
  ddlCountry.DataValueField = "CountryId";
  ddlCountry.DataSource= BLL.Country.GetCountry(string.Empty);
  ddlCountry.DataBind();

* 这里绑定工作正常。但我不确定它是否是最佳选择。请给我建议。

       System.Collections.IEnumerator lst= BLL.Country.GetCountry(string.Empty).GetEnumerator();
        while(lst.MoveNext())
        {
            string s = ((DAL.Entity.ORM.Country)(lst.Current)).Countryname;

         /* This is the main issue. To get data from [current]
         reference of [DAL.Entity.ORM.Country] is required.
         It is strongly not good practice to keep reference
         of DAL in PL. */
        }

使用带有存储过程的 EF 从数据库中获取数据并在 PL 中独立使用这些数据的最佳方法是什么?

使用静态方法是否安全?

请给我建议。

【问题讨论】:

    标签: loops stored-procedures entity-framework-4 data-access-layer


    【解决方案1】:
    1. 理想情况下,您不想在 PL 中引用您的 DAL。您可以与您的 PL 和 BL 共享类型。 BL 会在返回之前将您的 DAL 类型转换为该类型。

    2. 对于您的示例,显示 yes 静态方法应该没问题。

    【讨论】:

    • 无论如何要跳过从数据库实体到业务实体的转换,因为在从数据库中获取多条记录时,每次在将数据 BAL 发送到 PL 之前,我都需要将数据库实体集合转换为业务实体集合? ??
    • 如果没有将它们分开,您的 PL 将需要了解 DAL。使用复制构造函数转换类型应该相当容易。这可以使用 automapper 或 valueinjecter 来简化。我个人喜欢 valueinjecter,因为它使用起来更简单。
    • 能否请您举个例子,在将集合从 DAL 对象返回到 BLL 对象时如何编写复制构造函数?
    • msdn.microsoft.com/en-us/library/ms173116.aspx - 复制构造函数和valueinjecter.codeplex.com - 值注入器。对于上面显示的复制构造函数示例,传递 DL 对象而不是相同的类型。
    • 是的,你是对的,有多种方法可以将 DAL 对象转换为 BAL 对象。但我担心性能。假设我们从数据库中获取 >100000 条记录并将它们转换为 BAL 对象将产生额外的开销。我有以下解决方案。请建议我可以接受吗? BAL 将溢出到以下两个项目:Domain.Model 和 Domain.Repository OR Domain.Model.Operation 每一层都有 Domain.Model 的引用,并将用于将数据从一层传输到另一层。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多