简体   繁体   English

导航到同一表的属性

[英]Navigation properties to the same table

I have the folling model in my project (EF5, DBContext, database first): 我的项目中有以下跟踪模型(EF5,DBContext,数据库优先):

Customer 顾客

 InvoiceAddress -> Addresses (table)
 DeliveryAddress -> Addresses (table)

So I'm having 2 foreign keys to the same table. 所以我在同一张桌子上有2个外键。

When I load the customer entity using the following statement: 当我使用以下语句加载客户实体时:

 var cst = ctx.Customers.Where(c => c.CustomerID == 2).SingleOrDefault();
     ctx.Entry(cst).Reference(c => c.InvoiceAddress).Load();

After the reference of the InvoiceAddress is loaded, the DeliveryAddress is also loaded. 加载InvoiceAddress的引用后,也会加载DeliveryAddress。 However this only happends when the invoice and delivery ID are the same. 但是,只有在发票和交货ID相同时才会发生这种情况。 When they are not equal, the DeliveryAddress is not loaded. 当它们不相等时,则不加载DeliveryAddress。 What is causing this behavior? 是什么导致此行为?

Here's an educated guess: 这是一个有根据的猜测:

When you eagerly reference an entity, you're SELECT ing it immediately. 当您急切地引用一个实体时,您将立即SELECT它。 When you get your data, entity manager creates the entities in EF sense. 当您获取数据时,实体管理器会以EF的方式创建实体 Since the DeliveryAddress and InvoiceAddress are effectively the same entity (same PK, if you had a composite key, it would have to be the same composite key), it uses the same instance to represent both of them, which also means that the both addresses get loaded - because why not? 由于DeliveryAddressInvoiceAddress实际上是相同的实体(相同的PK,如果您具有复合键,则必须是相同的复合键),因此它使用相同的实例来表示它们两者,这也意味着这两个地址被加载-为什么不呢? It's exactly the same entity, the data is pointing to the same row in the DB. 它是完全相同的实体,数据指向数据库中的同一行。 References are shared and it uses less memory. 引用是共享的,它使用较少的内存。

If the PKs are different, then the invoice and delivery addresses are represented by different entities, loading one won't affect the other. 如果PK不同,则发票和交货地址由不同的实体表示,加载一个不会影响另一个。

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

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