简体   繁体   English

违反主要密钥实体框架代码

[英]Violation of primary key Entity Framework Code First

I have started with C# and I wanted to make my own DB. 我已经开始使用C#了,我想创建自己的数据库。

I have two models 我有两个型号

public class AModel 
{
    public Guid ID { get; private set; }
    public string Name { get; set; }
    public int Count { get; set; }
    public AModel()
    {
        this.ID = Guid.NewGuid();
    }
}

public class BModel 
{
    public Guid ID { get; private set; }
    public string Name { get; set; }
    public AModel Model { get; set; }
    public BModel()
    {
        this.ID = Guid.NewGuid();
    }
}

When I try to save BModel to DB, I get this error: 当我尝试将BModel保存到DB时,我收到此错误:

Violation of PRIMARY KEY constraint 'PK_dbo.AModels'. 违反PRIMARY KEY约束'PK_dbo.AModels'。 Cannot insert duplicate key in object 'dbo.AModels'. 无法在对象'dbo.AModels'中插入重复键。 The duplicate key value is (48ee1711-8da4-46c1-a714-19e985211fed).\\r\\nThe statement has been terminated. 重复键值为(48ee1711-8da4-46c1-a714-19e985211fed)。\\ r \\ n语句已终止。

I thought it would be solved by this 我以为它会被解决

modelBuilder.Entity<BModel>().HasRequired(t => t.Model).WithMany();

but it looks like I am completely lost. 但看起来我完全迷失了。 Could anybody help me with this simple example? 这个简单的例子可以帮助我吗?

Your comment reveals vital information. 您的评论揭示了重要信息。 When you add that AModel from your combobox to your BModel, it will have become detached from your DbContext by then. 当您将组合框中的AModel添加到BModel时,它将在那时与您的DbContext分离。 When you then add it to your model, Entity Framework will think that you have a new object. 然后,当您将其添加到模型中时,Entity Framework会认为您有一个新对象。

Since you have your Ids configured as DatabaseGenerationOptions.None, it will use the primary key you provide yourself. 由于您已将Ids配置为DatabaseGenerationOptions.None,因此它将使用您自己提供的主键。 In your case this is the PK of the detached object. 在您的情况下,这是分离对象的PK。 Thus, when EF tries to insert this entry it will throw the above exception because an entity with that key is already in there. 因此,当EF尝试插入此条目时,它将抛出上述异常,因为具有该键的实体已经在那里。

There are a few ways to solve this: 有几种方法可以解决这个问题:

  • Retrieve the existing entity 检索现有实体

This entity will be attached to your context upon retrieval, allowing you to use this. 此实体将在检索时附加到您的上下文,允许您使用它。 This means an extra lookup however: first to get them into the combobox and then to use the Id from the entity in the combobox to retrieve it again from the database. 这意味着额外的查找:首先将它们放入组合框中,然后使用组合框中实体的Id从数据库中再次检索它。

Example usage: 用法示例:

AModel Get(AModel detachedModel)
{
    using(var context = new MyContext())
    {
        return context.AModels.Single(x => x.ID == detachedModel.ID);
    }
}
  • Attach the existing model 附加现有模型

This should just make Entity-Framework aware that the entity already exists in the database. 这应该只是让实体框架意识到该实体已经存在于数据库中。

using(var context = new MyContext())
{
    context.AModels.Attach(detachedModel);
}

Other ways to attach is by setting the state to Unchanged 其他附加方法是将状态设置为Unchanged

context.Entry(detachedModel).State = EntityState.Unchanged;

or Modified (in case you also changed values) 或修改(如果您也更改了值)

context.Entry(detachedModel).State = EntityState.Modified;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Entity Framework代码第一个链接表中违反PRIMARY KEY约束 - Violation of PRIMARY KEY constraint in Entity Framework code first link table 首先使用实体​​框架代码保存分离的对象图会导致主键冲突 - Save detached object graph using Entity Framework code first causes Primary Key violation 首先删除实体框架代码中的主键 - deleting primary key in entity framework code first 实体框架-代码优先-没有共享主键时的实体拆分 - Entity Framework - Code First - Entity Splitting When There Is No Shared Primary Key 实体框架代码优先-通过主键将子实体添加到父实体 - Entity Framework Code First - Add Child Entity to Parent by Primary Key 违反 Entity Framework Core 中的 PRIMARY KEY 约束 - Violation of PRIMARY KEY constraint in Entity Framework Core 实体框架外键作为主键代码优先 - Entity Framework Foreign Key as Primary Key Code First 实体框架代码优先 - 非主键字段的外键 - Entity Framework Code First - Foreign Key to non primary key field 具有复合主键的实体框架“主键的违规” - Entity Framework “Violation of primary key” with composite primary key 实体框架-代码优先-共享主键一对多关系 - Entity Framework - Code first - One to Many relationship with shared primary key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM