【问题标题】:Multiplicity constraint violated Entity framework 6多重性约束违反了实体框架 6
【发布时间】:2018-11-29 09:52:39
【问题描述】:

我有一些我不明白的地方。 This 与我的情况类似。 我有 BaseEntity、Product、Supplier、Contract 和 ProductSupplierForContract 实体,都继承自 BaseEntity。

基础实体:

public class BaseEntity
{
    public int ID { get; set; }
    // other properties that are not entities by themself
}

产品实体:

[Required]
public ICollection<Supplier> Suppliers { get; set; }

[Required]
public ICollection<ProductSupplierForContract> ProductSupplierForContracts  { get; set; }

public  ICollection<Contract> Contracts { get; set; }

供应商实体:

public ICollection<ProductSupplierForContract> ProductSupplierForContracts  { get; set; }
public ICollection<Product> Products { get; set; }

ProductSupplierForContract 实体:

public string ProductnumberValue { get; set; }    

public Supplier Supplier { get; set; }
public int Supplier_Id { get; set; }

public Product Product { get; set; }
public int Product_Id { get; set; }

public Contract Contract { get; set; }
public int? Contract_Id { get; set; }

合同实体:

[Required]
public ICollection<Product> Products { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }

以下场景必须是可能且允许的: 一份合同可以包含来自不同供应商的 1 个产品的多个实例。 因此,我创建了 ProductSupplierForContract (PSFC) 实体,它将持有 1product-1supplier-1productnumber (value) -1contract 的这种关系。

当我编辑已经有 1 个 PSFC 实例的 1 个现有产品,并添加另一个持有另一个 PK、ProductId 和 SupplierId 的 PSFC 实例时,我收到此错误:

{"Multiplicity constraint violated. The role 'ProductSupplierForContract_Product_Target' of the relationship 'ContractCare.Models.ProductSupplierForContract_Product' has multiplicity 1 or 0..1."}

我不明白为什么,因为不是这样我才能拥有:

PSFC 1 
PK 1
ProductId 1
SupplierId 1

PSFC 2
PK 2
ProductId 1
SupplierId 2

为什么我应该(如上面链接帖子中所述)在产品上具有多对多关系 PSFC?

感谢您的任何反馈! 亲切的问候。

【问题讨论】:

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


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    扩展Aparna Gadgil 提供的链接,Arturo Hernandez 发布的其中一个 cmets 解决了我遇到的错误,因此我将标记为已解决,因为我最初的问题是错误。

    引用:

    问题是应该分配 detachedChild.parent 附加父母。

    foreach(var detachedEntity in detachedEntities)
    {
     attachedEntity.ChildEntities.Add(detachedEntity); 
     detachedEntity.ParentEntity = attachedEntity;
    }
    

    就我而言,我必须将父实体(我们正在更新的产品)附加到 ProductSupplierForContract.Product。创建答案中建议的新实体对我来说已经是这种情况,而附加它等其他事情对我来说并没有解决。

    由于我没有发布任何关于我如何执行此操作的代码,因此能够帮助我并不是很有帮助,我肯定会在未来尝试更具体:)。

    诚挚的问候,谢谢!

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多