读取实体的属性正在改变我在另一个属性上覆盖的ID

时间:2015-03-20 11:51:17

标签: c# asp.net-mvc entity-framework entity-framework-6

我有这个实体:

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时,我分配的值被覆盖,因为懒惰加载?

注意:如果我要在var someTempPlaceHolder = order.BillingContact.Id;作业上方添加DeliveryContact.Id,那么一切正常,因为我已经加载了BillingContact

有什么想法吗?

p.s如果我再次运行上面的代码,则会分配正确的ID,因此它肯定是导致问题的第一个负载。

1 个答案:

答案 0 :(得分:0)

好的,我实际上找到了答案,但稍后调试了一个单独的问题。基本上,这是延迟加载。

首次访问该属性时,它会从数据库中读取值。 这包括设置值

所以order.DeliveryContact = myValue实际上会在第一次从数据库中获取值,然后下一个赋值将覆盖它。

它在调试时起作用,因为我将鼠标悬停在值上并读取它以进行检查。