简体   繁体   English

使用实体框架检索相关实体

[英]Retrieve related entity with entity framework

实体框架中是否有一种方法可以让我们知道两个实体是否相关?

Let's say your variables are all attached to the same context. 假设您的变量都附加到同一上下文。 You want to know if your bar1 variable is one of the bar values in the foo.bars collection. 您想知道bar1变量是否是foo.bars集合中的bar值之一。 You could just do: 您可以这样做:

theyAreEqual = foo.bars.Contains(bar1);

If your entity variables are not attached to the context, then you might have different variables that logically refer to the same db records, but are actually pointers to different objects. 如果您的实体变量未附加到上下文,那么您可能拥有不同的变量,这些变量在逻辑上引用相同的db记录,但实际上是指向不同对象的指针。 So, you'd need to compare the key values: 因此,您需要比较关键值:

theyAreLogicallyEqual = foo.bars.Select(b => b.BarId).Contains(bar1.BarId);

I assume you know about this, but for others reading this answer, the differences in value and reference type equality is important here. 我想您知道这一点,但是对于其他阅读此答案的人来说, 值和引用类型相等性的区别在这里很重要。

You can use Linq to Entities. 您可以对实体使用Linq。 You can match every object in entity1 and check if there is a corresponding data/object entity in entity2. 您可以匹配entity1中的每个对象,并检查entity2中是否存在对应的数据/对象实体。

using (NorthwindEntities nw = new NorthwindEntities())    
{    
       var cusotmers = from c in nw.Customers    
                       where c.City == "London"    
                       select c;    
}

You can find more info here: http://msdn.microsoft.com/en-us/library/cc161164.aspx 您可以在这里找到更多信息: http : //msdn.microsoft.com/en-us/library/cc161164.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM