EF 4.1 - 更新子集合的属性

时间:2011-09-04 20:32:41

标签: asp.net-mvc-3 entity-framework-4.1 automapper

我一直在低调搜索,我被困在这里。

我在MVC3应用程序中使用EF 4.1,使用Service / Repository / UnitOfWork模式和AutoMapper来映射我的模型和实体。

所以我有一个非常基本的情况;我有ChildProducts的集合,其集合为PriceTiers

我的观点模型如下:

AddEditChildProductModel

public class AddEditChildProductModel
    {
        #region "Fields/Properties"
        public ActionType ActionType { get; set; }
        public string FormAction { get; set; }

        public int ID { get; set; }
        public int ProductID { get; set; }

        public string Sku { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public decimal Cost { get; set; }
        public decimal MSRP { get; set; }
        public decimal RetailPrice { get; set; }

        public int Servings { get; set; }
        public decimal Weight { get; set; }

        public bool Display { get; set; }
        public int DisplayIndex { get; set; }

        public IEnumerable<AddEditPriceTierModel> PriceTiers { get; set; }

        #endregion

        #region "Constructor(s)"

        #endregion

        #region "Methods"

        #endregion
    }

AddEditPriceTierModel

public class AddEditPriceTierModel
    {
        #region "Fields/Properties"
        public int ID { get; set; }
        public int ChildProductID { get; set; }
        public decimal Price { get; set; }
        public int QuantityStart { get; set; }
        public int QuantityEnd { get; set; }
        public bool IsActive { get; set; }
        #endregion

        #region "Constructor(s)"

        #endregion

        #region "Methods"

        #endregion
    }

在控制器操作中,我只是尝试映射已更改的PriceTier属性:

public ActionResult EditChildProduct(AddEditChildProductModel model)
        {
            if (!ModelState.IsValid)
                return PartialView("AddEditChildProduct", model);

            ChildProduct childProduct = productService.GetChildProductByID(model.ID);
            AutoMapper.Mapper.Map<AddEditChildProductModel, ChildProduct>(model, childProduct);
            UnitOfWork.Commit();

            return ListChildProducts(model.ProductID);
        }

我收到了这个错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

当踏入动作时,模型/实体被正确映射,我不明白!!

1 个答案:

答案 0 :(得分:1)

Eranga是对的。我猜测你的productService在返回ChildProduct之前没有在ef上下文中调用AsNoTracking。如果不是,这意味着它返回的内容仍然附加到上下文。当automapper做了它的事情时,它取代了整个集合,它可以孤立不属于表单提交的附加子实体。由于孤儿不具有非空外键,因此必须在调用SaveChanges之前将其从上下文中删除。如果他们不是,你会得到这个臭名昭着的例外。

另一方面,如果您的productService在返回实体之前在上下文上调用AsNoTracking,它将不会跟踪更改,也不会尝试删除由automapper创建的集合中不存在的任何孤立项。