使用脱离状态的相关实体更新对象

时间:2012-03-19 19:20:15

标签: asp.net asp.net-mvc-3 entity-framework-4

当我从实体框架查询时,我总是以分离状态查询,以便检索到的记录可以存储在缓存中以供后续请求使用。

现在我有一个用户可以编辑的表单,其中包含父记录,然后是两个父记录列表。

当数据发布到服务器时,我使用我的视图模型并使用AutoMapper将它们映射到实体框架对象中。数据看起来很好; AutoMapper正确映射数据。

当我附加对象以便我可以更新它时,会抛出异常:A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship

public static void UpdateOrder(ShippingOrder shippingOrder) {
    using (OrderEntity orderContext = new OrderEntity()) {
        //Exception happens here
        orderContext.ShippingOrders.Attach(shippingOrder);
        //Update the order itself; mark the order has being modified so the EF will update it.
        orderContext.ObjectStateManager.ChangeObjectState(shippingOrder, System.Data.EntityState.Modified);
        //Perform the update.
        orderContext.SaveChanges();
    }
}

EntityFramework(EF)似乎认为我的键没有排队,但我不确定什么是不正确的。外键属性确实有正确的值,所以我不确定它正在检查什么。有没有人有任何想法?

3 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

ShippingOrder existingShippingOrder = orderContext.ShippingOrders.Find(shippingOrder.ID);
orderContext.Entry(existingShippingOrder ).CurrentValues.SetValues(shippingOrder);

答案 1 :(得分:0)

而不是

orderContext.ObjectStateManager.ChangeObjectState(shippingOrder, System.Data.EntityState.Modified);

试试这个

orderContext.Entry(ShippingOrder).State = EntityState.Modified;

答案 2 :(得分:0)

解释here

  

插入或更新模式某些应用程序的常见模式是   将实体添加为新实体(导致数据库插入)或附加   现有实体并将其标记为已修改(生成数据库)   更新)取决于主键的值。例如,何时   使用数据库生成的整数主键通常会对其进行处理   具有零键的实体和具有非零键的实体   现有。可以通过设置实体状态来实现此模式   基于主键值的检查。例如:

public void InsertOrUpdate(DbContext context, Unicorn unicorn)
{
    context.Entry(unicorn).State = unicorn.Id == 0 ?
                                   EntityState.Added :
                                   EntityState.Modified;
    context.SaveChanges();
}

你可以尝试

public static void UpdateOrder(ShippingOrder shippingOrder) {
    using (OrderEntity orderContext = new OrderEntity()) {       
        orderContext.Entry(shippingOrder).State = shippingOrder.Id==0?
                                                  EntityState.Added :
                                                  EntityState.Modified;

        orderContext.SaveChanges();
    }
}

<强>更新

对于ObjectContext课程,您可以尝试

 public static void UpdateOrder(ShippingOrder shippingOrder) {
        using (OrderEntity orderContext = new OrderEntity()) {                  
            orderContext.ObjectStateManager.ChangeObjectState(shippingOrder, EntityState.Modified);    
            orderContext.SaveChanges();
        }
    }