针对实体读取属性会更改我在另一个属性上覆盖的 ID



我有这个实体:

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.Idorder.DeliveryContact.Id都是4viewModel.DeliveryContact.Id2.

当我处理第一个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实际上第一次从数据库中获取值,然后下一个赋值将覆盖它。

它在调试时有效,因为我会将鼠标悬停在值上并读取它以检查它。

最新更新