我有 .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/