使用.Find()& .include()在同一查询上 [英] Using .Find() & .Include() on the same query

查看:126
本文介绍了使用.Find()& .include()在同一查询上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从具有存储库的支架模板自动生成以下方法:-

I have the following method automatically generated from the scaffold template with repository:-

public Group Find(int id)
{
    return context.Groups.Find(id);
}

但是,由于Groups对象具有两个我需要的导航属性,所以我想要包含 .Include ,所以我将 .find 替换为 .where :-

But since the Groups object has two navigation properties which I need , so I wanted to include the .Include, so I replace the .find with .where :-

public Group Find(int id)
{
    return context.Groups.Where(c=>c.GroupID==id)
                         .Include(a => a.UserGroups)
                         .Include(a2 => a2.SecurityRoles)
                         .SingleOrDefault();
}

但是我的问题是如何应用。在 .find()中包含,而不是使用 .Where()

But my question is how can I apply the .Include with the .find() instead of using .Where()?

推荐答案

我只是在考虑find的实际作用。 @lazyberezovsky是正确的包含并发现​​不能相互结合使用。我认为这是故意的,这就是为什么:

I was just thinking about what find actually does. @lazyberezovsky is right include and find cant be used in conjunction with each other. I think this is quite deliberate and here's why:


DbSet的Find方法使用主键值尝试查找
由上下文跟踪的实体。如果在
上下文中未找到实体,则将向数据库发送查询以在其中找到实体
。如果在上下文中或数据库中未找到实体,则返回Null。

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

查找与在两种重要方式下使用查询不同:

Find is different from using a query in two significant ways:


  • 只有在上下文中未找到具有给定键的实体时,才进行数据库往返。

  • Find将返回处于已添加状态的实体。也就是说,查找将返回已添加到上下文但尚未保存
    的实体。

(来自 http://msdn.microsoft.com/en-us/data/jj573936.aspx

由于find是一种优化的方法,因此可以避免访问服务器的麻烦。如果您已经跟踪了实体,那就太好了,因为EF可以更快地返回它。

Because find is an optimised method it can avoid needing a trip to the server. This is great if you have the entity already tracked, as EF can return it faster.

但是,如果不仅仅是我们追求的这个实体(例如,我们想包括一些额外的数据)无法知道是否已从服务器加载此数据。尽管EF可能会结合联接进行此优化,但是由于它对数据库状态进行了假设,因此容易出错。

However if its not just this entity which we are after (eg we want to include some extra data) there is no way of knowing if this data has already been loaded from the server. While EF could probably make this optimisation in conjunction with a join it would be prone to errors as it is making assumptions about the database state.

我想包括但不包括能够一起使用是一个非常刻意的决定,以确保数据完整性和不必要的复杂性。当您要进行联接以始终转到数据库执行该联接时,它要干净得多且简单得多。

I imagine that include and find not being able to be used together is a very deliberate decision to ensure data integrity and unnecessary complexity. It is far cleaner and simpler when you are wanting to do a join to always go to the database to perform that join.

这篇关于使用.Find()& .include()在同一查询上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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