IE可在延迟加载EF中使用 [英] IEnumerable in lazy-loading EF

查看:80
本文介绍了IE可在延迟加载EF中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆