我有这个实体:
public class SalesOrder : BaseEntity
{
public virtual CustomerContact DeliveryContact { get; set; }
public virtual CustomerContact BillingContact { get; set; }
}
然后我运行以下代码:
if (viewModel.DeliveryContact != null && viewModel.DeliveryContact.Id.ToInt() > 0)
order.DeliveryContact = customerService.GetContactById(viewModel.DeliveryContact.Id.ToInt());
if (order.BillingContact.Id == 0)
order.BillingContact = order.DeliveryContact; //This doesn't actually get hit.
当我开始时,order.BillingContact.Id
和order.DeliveryContact.Id
都是4
。 viewModel.DeliveryContact.Id
是2
.
当我处理第一个if statement
时,order.DeliveryContact.Id
现在读取2
,就像我期望的那样,但是当下一个if语句order.DeliveryContact.Id
重置回4
时。似乎第一次读取order.BillingContact
时,它会覆盖我分配给DeliveryContact
的值。我可以通过在order.BillingContact
上使用手表来重现这一点,因为当我添加手表时,我也会看到order.DeliveryContact
值发生变化。
仅当送货和帐单联系人都以相同的 ID(在本例中为 4(开始时,才会发生这种情况。
这似乎是非常奇怪的行为。在这一点上,我唯一的猜测是,因为它们以相同的ID开头,实体框架对两个属性使用相同的引用,因此当我第一次阅读BillingContact时,由于延迟加载,我分配的值被覆盖了?
注意:如果我要在DeliveryContact.Id
分配上方添加var someTempPlaceHolder = order.BillingContact.Id;
,那么一切都在我加载BillingContact
时起作用。
有什么想法吗?
p.s 如果我第二次运行上面的代码,则会分配正确的 ID,因此它绝对是导致问题的第一次加载。
好的,我实际上在一段时间后调试一个单独的问题时找到了答案。基本上,这取决于延迟加载。
首次访问该属性时,它会从数据库中读取值。这包括设置值
因此,order.DeliveryContact = myValue
实际上第一次从数据库中获取值,然后下一个赋值将覆盖它。
它在调试时有效,因为我会将鼠标悬停在值上并读取它以检查它。