简体   繁体   中英

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. 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. 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. You can match every object in entity1 and check if there is a corresponding data/object entity in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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