c# - 使用后代代理类更改 EF 实体

标签 c# database entity-framework data-access-layer

我有 .Net 4.0 应用程序,它使用 EntityFramework 5.0 从 MS SQL 数据库访问数据。

我使用数据库优先方法。所有表都映射到 POCO 实体,该实体具有其他属性,其中包含从 Web 服务接收的实体。

数据库:

WH_Product (Id, NomenklatureId, SeriesId, Quantity)

服务有这样的数据:

Nomenklature (Id, Name, Producer...)
Series (Id, Number, Date...)

POCO实体:

Product (Id, NomenklatureId, Nomenklature, SeriesId, Series, Quantity)

我对存储库实现有疑问。我需要为 Nomenklature 和 Series 属性实现延迟加载。

我制作了 ProductProxy 类,它实现了这样的加载:

public class ProductProxy:Product
{

   private Nomenklature _nomenklature;
   public override Nomenklature Nomenklature
   {
      get
      {
         if (_nomenklature==null)
         {
            _nomenklature = <code for load Nomenklature from webService by base.NomenklatureId>
         }
         return _nomenklature;
      }
   }

   private Series _series;
   public override Series Series
   {
      get
      {
         if (_series==null)
         {
            _series = <code for load Series from webService by base.NomenklatureId>
         }
         return _series;
      }
   }
}

然后在 DbContext 中将 Person 类更改为 PersonProxy 类。

public class ProductContext:DbContext
{
   ...
   public DbSet<PersonProxy> Person {get; set;}
   ...
}

加载方法:

public List<Person> GetPersons()
{
    using (var ctx = new ProductContext())
    {
        var persons = ctx.Person.AsEnumerable().Cast<Person>().ToList();
        return persons;
    }
}

问题: 这是在没有 AsEnumerable().Cast() 的情况下实现 GetPersons 方法的更好方法吗? 这是另一种使用后代代理类型更改实体类型的方法吗?

最佳答案

Proxy模式正在利用多态性(“OOP 的三大支柱”之一),对象的使用者认为它处理的是Person。而实际上他正在处理一个PersonProxy .这是可能的,因为 PersonProxy Person因为它源自它。

这就是为什么你可以这样写:

Person person = new PersonProxy();

那么在你的情况下,你的 GetPersons()方法可以简单地返回 IEnumerable<Person> ,如下:

public IEnumerable<Person> GetPersons()
{
    using (var ctx = new ProductContext())
    {
        return ctx.Person;
    }
}

关于c# - 使用后代代理类更改 EF 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18438716/

相关文章:

c# - 在 C# 中使用 using 语句强制执行完整命名空间

c# - 如何有效地存储/检索有关网格边缘的数据?

c# - 尝试从另一个线程访问复杂对象时出现 InvalidOperationException

database - Hibernate 不在数据库中创建表

c# - 防止 "' System.DateTime' 失败,因为物化值为 null"

c# - 获取多列的总和

c# - 调用构造函数的顺序

java - java中数据库中的洗牌

c# - EF 核心 : Database First Conversion : Foreign Key wrong column

mysql - 为什么我收到错误 #1005 - 无法创建表 'FinalProject.#sql-3875_a1' (errno : 150)