我在EF Code First中有两个模型:
I have two models in EF Code First:
public class Book { public int Id { get; set; } public virtual IEnumerable<Page> Pages { get; set; } } public class Page { public int Id { get; set; } public int BookId { get; set; } public Book Book { get; set; } }从数据库加载Book模型时,Pages属性为Null。但是,当替换IEnumerable => ICollection时,延迟加载将起作用,并且页面将从数据库填充。 IEnumerable和延迟加载如何一起使用?
When loads a Book model from DB, Pages property is Null. But when replace IEnumerable => ICollection, lazy loading works and Pages fills from DB. How use IEnumerable and lazy loading together?
推荐答案IEnumerable 是不可变的集合您无法修改(添加或删除)。 EF不支持此类型,因为EF内部需要修改模型中的集合。
IEnumerable is immutable collection which you cannot modify (add or remove). EF does not support this type because internally EF need to modify collection in model.
使用 ICollection 代替, ICollection 继承自 IEnumerable ,因此它不仅仍然具有延迟执行(延迟加载)的目的,还拥有更多修改集合的方法。
Use ICollection instead, ICollection inherits from IEnumerable so it not only still get deferred execution (lazy loading) purpose but also has more methods to modify collection.
更多推荐
IE可在延迟加载EF中使用
发布评论