我已经搜索了嗨,很低,我被困在这里。

我在MVC3应用程序中使用EF 4.1,并带有服务/存储库/单位工程模式和自动应用程序来映射我的模型和实体。

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

我的视图模型看起来像这样:

AdditchildProductModel

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
    }

AdditPricEtiermodel

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.

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

有帮助吗?

解决方案

Eranga是对的。我猜想您的产品服务在返回儿童产品之前不会在EF上下文上称呼为“无关”。如果没有,这意味着它返回的内容仍然附加到上下文上。当Automapper做事时,它会取代整个集合,这可以孤儿,而不是表格提交的一部分。由于孤儿没有非无效的外键,因此必须在调用savechanges之前从上下文中删除它们。如果不是,您会得到这个臭名昭著的例外。

另一方面,如果您的产品服务在返回实体之前在上下文上调用Asnotracking,则不会跟踪更改,并且不会尝试删除Automapper创建的集合中不存在的任何孤儿。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top