为什么实体框架需要一个ICollection来进行延迟加载? [英] Why does the entity framework need an ICollection for lazy loading?
问题描述
我想写一个丰富的域类,如
I want to write a rich domain class such as
public class Product
{
public IEnumerable<Photo> Photos {get; private set;}
public void AddPhoto(){...}
public void RemovePhoto(){...}
}
但实体框架(V4代码第一种方法)需要一个ICollection类型进行延迟加载!上述代码不再像设计一样工作,因为客户端可以绕过AddPhoto / RemovePhoto方法,直接调用ICollection上的add方法。这不是很好。
But the entity framework (V4 code first approach) requires an ICollection type for lazy loading! The above code no longer works as designed since clients can bypass the AddPhoto / RemovePhoto method and directly call the add method on ICollection. This is not good.
public class Product
{
public ICollection<Photo> Photos {get; private set;} //Bad
public void AddPhoto(){...}
public void RemovePhoto(){...}
}
尝试使用EF4实现DDD变得非常令人沮丧。为什么选择ICollection进行延迟加载?
It's getting really frustrating trying to implement DDD with the EF4. Why did they choose the ICollection for lazy loading?
我如何克服这个问题? NHibernate为我提供了更好的DDD体验吗?
How can i overcome this? Does NHibernate offer me a better DDD experience?
推荐答案
我想我找到了解决方案...更多详情请看这里: a href =http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/ =noreferrer> http://social.msdn .microsoft.com /论坛/ en-US / adodotnetentityframework / thread / 47296641-0426-49c2-b048-bf890c6d6af2 /
I think i found the solution...See here for more details: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/
本质上你想让ICollection类型受保护,并将其用作公共IEnumerable的支持集合
Essentially you want to make the ICollection type protected and use this as the backing collection for the public IEnumerable
public class Product
{
// This is a mapped property
protected virtual ICollection<Photo> _photos { get; set; }
// This is an un-mapped property that just wraps _photos
public IEnumerable<Photo> Photos
{
get { return _photos; }
}
public void AddPhoto(){...}
public void RemovePhoto(){...}
}
为了延迟加载工作,类型必须实现ICollection,访问必须是公共的或受保护的。
For lazy loading to work the type must implement ICollection and the access must be public or protected.
这篇关于为什么实体框架需要一个ICollection来进行延迟加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!