实体框架4.1代码第一 - 控制加载 [英] Entity Framework 4.1 Code First - Controlling Eager Loading

查看:102
本文介绍了实体框架4.1代码第一 - 控制加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有一个父类有20,000个子对象,我只想检索一个子集子对象是可能的吗?



如果是这样的话,我该如何编写查询?



例如:



我有一个名为Book的实体,它有一些相关的评论:

 code> public class Book {
public int BookId {get;组; }
public string BookName {get;组; }
public ICollection< Review>点评{get;组; }
}

public class Review {
public int ReviewId {get;组; }
public int Score {get;组; }
public Book Book {get;组;
}

我想做一些类似的事情:

  var bookWithFirstTwentyReviews = db.Books.Where(b => b.BookId == 1).Include(Reviews)。FirstOrDefault(); 

但是,我只想包括20条评论,而不是全部20,000条

解决方案

Include 不允许任何过滤或排序。一个选择是使用显式加载:

  //加载书没有评论(第一个往返数据库)
var book = context.Books.Where(b => b.Id == id).SingleOrDefault();

//然后加载已过滤的集合的评论(第二往返数据库)
if(book!= null)
context.Entry(book).Collection(b => ; b.Reviews).Query()。Take(20).Load();

它需要对数据库进行两次往返(这不一定是坏的,性能上的,因为渴望加载另一方面可能会带来许多重复的数据)。



另一种方法是在上下文中使用投影并利用关系跨度。这是@BrokenGlass(现在删除)所示的解决方案。


Is it possible to control eager loading of child objects.

If I had a parent class that has 20,000 child objects and I only wanted to retrieve a subset of those child objects is it possible?

How would I write the query to do that if it is?

For Example:

I have an Entity called Book which has a number of related Reviews:

public class Book {
    public int BookId { get; set; }
    public string BookName { get; set; }
    public ICollection<Review> Reviews { get; set; }
}

public class Review { 
    public int ReviewId { get; set; }
    public int Score { get; set; }
    public Book Book { get; set; }
}

I want to do something like:

var bookWithFirstTwentyReviews = db.Books.Where(b => b.BookId == 1).Include("Reviews").FirstOrDefault();

But I only want to include 20 reviews, not all 20,000

解决方案

Include doesn't allow any filtering or sorting. One option is to use explicite loading:

// load book without Reviews (1st roundtrip to DB)
var book = context.Books.Where(b => b.Id == id).SingleOrDefault();

// then load a filtered collection of Reviews (2nd roundtrip to DB)
if (book != null)
    context.Entry(book).Collection(b => b.Reviews).Query().Take(20).Load();

It requires two roundtrips to the database though (which is not necessarily bad, performancewise, because eager loading on the other hand comes with potentially lots of duplicated data).

The other approach is to use a projection and leverage relationship span in the context. This was the solution shown by @BrokenGlass (deleted now).

这篇关于实体框架4.1代码第一 - 控制加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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