简体   繁体   English

实体框架 ALTER TABLE 语句与 FOREIGN KEY 约束冲突

[英]Entity Framework The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

On updating database in Entity Framework , Code first Migration, I am getting this error:在 Entity Framework 中更新数据库时,代码优先迁移,我收到此错误:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Clients_dbo.MedicalGroups_MedicalGroupId". ALTER TABLE 语句与 FOREIGN KEY 约束“FK_dbo.Clients_dbo.MedicalGroups_MedicalGroupId”相冲突。 The conflict occurred in database "hrbc", table "dbo.MedicalGroups", column 'Id'.冲突发生在数据库“hrbc”、表“dbo.MedicalGroups”、“Id”列中。

This is my class:这是我的课:

public partial class Client
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? MedicalGroupId { get; set; }
    [ForeignKey("MedicalGroupId")]
    public virtual MedicalGroups MedicalGroup { get { return _MedicalGroup; } set { _MedicalGroup = value; } }
}

Here is my 2nd class:这是我的第二堂课:

public partial class MedicalGroups
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

And this is my migration which I am trying to apply:这是我尝试申请的迁移:

public override void Up()
{
    AddForeignKey("dbo.Clients", "MedicalGroupId", "dbo.MedicalGroups", "Id");
    CreateIndex("dbo.Clients", "MedicalGroupId");
}

检查数据库中是否存在与 FK 约束冲突导致创建失败的现有数据。

I think @Cory was getting you close to the correct solution, you just did not take the time to investigate.我认为@Cory 让您接近正确的解决方案,您只是没有花时间进行调查。

In add-migration code, the migration probably generated在添加迁移代码中,迁移可能生成

public override void Up()
{
AddColumn("dbo.ClientContacts", "FamilialRelationshipId", c => c.Int(nullable: false));
CreateIndex("dbo.ClientContacts", "FamilialRelationshipId");
AddForeignKey("dbo.ClientContacts", "FamilialRelationshipId", "dbo.FamilialRelationships",        "FamilialRelationshipId");
}

Notice nullable:false;注意 nullable:false; If your Model had an Id of int instead of int?如果您的模型的 ID 是 int 而不是 int? (nullable int) the migration code will set nullable to false. (nullable int) 迁移代码会将 nullable 设置为 false。 Your model shows you are using a non-nullable int which defaults to 0, and you probably don't have a foreign key item with a value of 0.您的模型显示您正在使用默认为 0 的不可为空的 int,并且您可能没有值为 0 的外键项。

Now, you will have to either create a default value, that exists in the foreign key table, or Create the Constraint with no check if you are using SQL Server to create the constraint.现在,您必须创建一个存在于外键表中的默认值,或者创建约束而不检查是否使用 SQL Server 创建约束。 Remember this though: If you decorate your property with a [DefaultValue(0)] attribute, it won't change the existing data, like a SQL Column Add would, if a default value was specified.不过请记住:如果您使用 [DefaultValue(0)] 属性装饰您的属性,则它不会更改现有数据,就像 SQL 列添加一样,如果指定了默认值。

I recommend you change your Model Class to allow a nullable int.我建议您更改模型类以允许可以为空的 int。 Then, in your seed method, create a simple method against dbcontext to update the new column with a default value, because the [DefaultValue] attribute in data annotations will not modify your data.然后,在您的种子方法中,针对 dbcontext 创建一个简单的方法以使用默认值更新新列,因为数据注释中的 [DefaultValue] 属性不会修改您的数据。

Add-Migration / Update-Database to create the column and constraint. Add-Migration / Update-Database 创建列和约束。 Next, modify your model if you desire to allow for a non-nullable int, and presuming you changed all rows to some valid value for the foreign key, Add-Migration / Update-database again.接下来,如果您希望允许不可为空的 int,并假设您将所有行更改为外键的某个有效值,请修改您的模型,再次添加迁移/更新数据库。 This gives you an unbroken chain in your model migration.这为您的模型迁移提供了一条不间断的链条。 Will come in handy later when you publish to a live site, because the flow of your data model changes will be intact.稍后当您发布到实时站点时会派上用场,因为您的数据模型更改流将保持不变。

  • Hope this helps.希望这会有所帮助。

This error is telling you that you are violating the foreign key constraint.这个错误告诉你你违反了外键约束。 To resolve you have a few solutions要解决您有几个解决方案

  1. Fix your data - Somewhere there are records in the Clients table that have a MedicalGroupId that does not exist in the in the MedicalGroups table.修复您的数据- Clients表中某处的记录具有MedicalGroups表中不存在的MedicalGroups Write a query to find out what IDs do not exist in the MedicalGroups table and manually fix the data yourself.编写查询以找出MedicalGroups表中不存在哪些 ID 并自己手动修复数据。
  2. Remove the foreign key constraint - Obviously if you remove the foreign key constraint you will no longer be bothered by this message.删除外键约束- 显然,如果删除外键约束,您将不再受到此消息的困扰。 Unfortunately the database will no longer enforce this relationship and might make this problem worse in the future.不幸的是,数据库将不再强制执行这种关系,并且将来可能会使这个问题变得更糟。
  3. Create constraint using WITH NOCHECK - You can create your foreign key constraint using the WITH NOCHECK option.使用WITH NOCHECK创建约束- 您可以使用WITH NOCHECK选项创建外键约束。 This option tells SQL Server to not apply this constraint to existing data.此选项告诉 SQL Server 不对现有数据应用此约束。 SQL Server WILL check this constraint in any future INSERTS/UPDATES/DELETES. SQL Server 将在以后的任何 INSERTS/UPDATES/DELETES 中检查此约束。

For others that may land here, there could be a really simple fix if you're using Code-First Entity Framework and just trying to add a new required column to a table with existing data.对于可能出现在这里的其他人,如果您使用代码优先实体框架并且只是尝试将新的必需列添加到具有现有数据的表中,则可能有一个非常简单的修复方法。

Note: Before you do this, just know that you will need to add a valid value to this new column for all existing rows.注意:在执行此操作之前,只需知道您需要为所有现有行的此新列添加一个有效值。 Think about what value you will add to the existing rows before proceeding.在继续之前考虑将向现有行添加什么值。 You may want to provide a value that indicates "Invalid" or "Unknown" to the required lookup table.您可能希望为所需的查找表提供一个指示“无效”或“未知”的值。

In your model, set the column to nullable by adding the ?在您的模型中,通过添加 ? after the int.在 int 之后。 Save and compile the model.保存并编译模型。 Run Update-Database.运行更新数据库。

Example:例子:

 [ForeignKey("Title")] public int? TitleId { get; set; }

In the db, update the table by replacing the NULL values with a valid lookup value.在数据库中,通过用有效的查找值替换 NULL 值来更新表。 In my case, I added "Unknown" to my Title lookup table and then bulk edited all rows to reference that lookup Id.就我而言,我在标题查找表中添加了“未知”,然后批量编辑所有行以引用该查找 ID。

Back in your model, remove the '?'回到您的模型中,删除“?” so the column is no longer nullable.所以该列不再可以为空。 Save and compile the model and then run Update-Database保存并编译模型,然后运行 ​​Update-Database

You should now be good to go.你现在应该可以走了。

this problem appear because your table is not empty.出现此问题是因为您的表不为空。 so you shoud add the new field without attaching it like foreign key.所以你应该添加新字段而不像外键一样附加它。 public int? MedicalGroupId { get; set; } public int? MedicalGroupId { get; set; } .And execute update-database command in package manage console. public int? MedicalGroupId { get; set; } 。而执行update-database中包命令管理控制台。 Then fill the field in this table(client) with the right data (value exists in MedicalGroupsId).然后用正确的数据填充此表(客户端)中的字段(值存在于 MedicalGroupsId 中)。 Insert the line to create the foreign key插入用于创建外键的行

[ForeignKey("MedicalGroupId")]
public virtual MedicalGroups MedicalGroup { get { return _MedicalGroup; } set { _MedicalGroup = value; } }

in the end execute the update-database command.最后执行update-database命令。 It will be ok.会没事的。

I got the solution of my Problem.我得到了我的问题的解决方案。 Problem is "data" which i have in my clients table.问题是我的客户表中的“数据”。 Because my client table have medicalgroupid values which are not actually exist that's why it is giving me error on foreign key constraint.因为我的客户端表具有实际上并不存在的医疗组 ID 值,这就是为什么它在外键约束上给我错误。

Update Client set MedicalGroupId = NULL

I had this issue as well with defaultValue set, gave:我在设置 defaultValue 时也遇到了这个问题,给出了:

"The object is dependent on column ALTER TABLE ALTER COLUMN failed because one or more objects access this column". “该对象依赖于列 ALTER TABLE ALTER COLUMN 失败,因为一个或多个对象访问此列”。

Ended up move the AddForeignKey/DropForeignKey to a new migration and ran them in separate update-database commands (dont excecute both migrations in one command then it failed for me.)最终将 AddForeignKey/DropForeignKey 移动到新的迁移并在单独的更新数据库命令中运行它们(不要在一个命令中执行两个迁移然后它对我来说失败了。)

    public override void Up()
    {
        CreateTable(
            "dbo.DecisionAccesses",
            c => new
            {
                Id = c.Int(nullable: false),
                Name = c.String(nullable: false, maxLength: 50),
            })
            .PrimaryKey(t => t.Id);

        CreateTable(
            "dbo.DecisionPersonStatus",
            c => new
            {
                Id = c.Int(nullable: false),
                Name = c.String(nullable: false, maxLength: 50),
            })
            .PrimaryKey(t => t.Id);

        AddColumn("dbo.DecisionForm_DecisionFields", "DecisionAccessId", c => c.Int(nullable: false, defaultValue: (int)DecisionAccess.Creator));
        AddColumn("dbo.DecisionMatterPersons", "DecisionPersonStatusId", c => c.Int(nullable: false, defaultValue: (int)DecisionAccess.Creator));
        CreateIndex("dbo.DecisionForm_DecisionFields", "DecisionAccessId");
        CreateIndex("dbo.DecisionMatterPersons", "DecisionPersonStatusId");
        //I moved outcommented to next migration and ran the migrations in separate steps to avoid: (The object is dependent on column ALTER TABLE ALTER COLUMN failed because one or more objects access this column)
        //AddForeignKey("dbo.DecisionForm_DecisionFields", "DecisionAccessId", "dbo.DecisionAccesses", "Id", cascadeDelete: true); 
        //AddForeignKey("dbo.DecisionMatterPersons", "DecisionPersonStatusId", "dbo.DecisionPersonStatus", "Id", cascadeDelete: true);
    }


    public override void Down()
    {
        //Moved to next migration
        //DropForeignKey("dbo.DecisionMatterPersons", "DecisionPersonStatusId", "dbo.DecisionPersonStatus");
        //DropForeignKey("dbo.DecisionForm_DecisionFields", "DecisionAccessId", "dbo.DecisionAccesses");
    }

Assuming your migrations are in correct order ie table associated with Foreign key will get created before the reference.假设您的迁移顺序正确,即与外键关联的表将在引用之前创建。 Follow the following steps:请按照以下步骤操作:

  1. Backup current database from SQL management studio (If required)从 SQL 管理工作室备份当前数据库(如果需要)
  2. Delete database from SQL management studio从 SQL 管理工作室删除数据库
  3. Type 'Update-Database'in Visual Studio 'Package Manager Console'在 Visual Studio 的“包管理器控制台”中键入“更新数据库”

Run the Add-Migration InitialCreate –IgnoreChanges command in Package Manager Console.在包管理器控制台中运行Add-Migration InitialCreate –IgnoreChanges命令。 This creates an empty migration with the current model as a snapshot.这将创建一个以当前模型作为快照的空迁移。

Run the Update-Database command in Package Manager Console.在包管理器控制台中运行Update-Database命令。 This will apply the InitialCreate migration to the database.这会将 InitialCreate 迁移应用到数据库。 Since the actual migration doesn't contain any changes, it will simply add a row to the __MigrationsHistory table indicating that this migration has already been applied.由于实际迁移不包含任何更改,因此它只会向 __MigrationsHistory 表添加一行,表明此迁移已被应用。

You can get more detail here : https://msdn.microsoft.com/en-us/library/dn579398(v=vs.113).aspx您可以在此处获得更多详细信息: https : //msdn.microsoft.com/en-us/library/dn579398(v=vs.113).aspx

This error can also happen if you have orphan records in the child table.如果子表中有孤立记录,也会发生此错误。 Clean up the database should resolve the issue.清理数据库应该可以解决问题。

I also received this message.我也收到了这个消息。 The problem was that the test data in the db was incorrect.问题是db中的测试数据不正确。 I didn't have validation on when I was testing and hence i had null values for IDs for fields that do not allow nulls.我在测试时没有验证,因此对于不允许为空的字段,我的 ID 为空值。 Once I fixed the data, the update-database command ran successfully.一旦我修复了数据,update-database 命令就成功运行了。

Had that issue but fortunately I was just building my tables.有这个问题,但幸运的是我只是在建我的桌子。 I only had a couple sample items in each table.我在每张桌子上只有几个示例项目。 Deleted all the rows in both tables then it worked.删除两个表中的所有行然后它工作。 I'm a noob so take it for what it's worth我是个菜鸟,所以就物有所值吧

You could also use data seeding via您还可以通过使用数据播种

modelBuilder.Entity<MedicalGroups>()
.HasData(new MedicalGroups { ... }, new MedicalGroups { ... })

in your DbContexts class OnModelCreating method.在您的 DbContexts 类 OnModelCreating 方法中。

That way you can insert all the MedicalData rows whos Id is missing from the referencing table.这样您就可以插入引用表中缺少 Id 的所有 MedicalData 行。 At least in my case the data got seeded bofere it was needed and update-database worked properly.至少在我的情况下,数据被播种了,这是需要的,并且更新数据库正常工作。

暂无
暂无

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

相关问题 实体框架迁移-与外键约束冲突的Alter表语句 - Entity Framework Migration - Alter Table Statement Conflicted with Foreign Key Constraint 实体框架代码第一个INSERT语句与FOREIGN KEY约束冲突 - Entity Framework code first INSERT statement conflicted with the FOREIGN KEY constraint INSERT 语句首先与实体框架数据库中的 FOREIGN KEY 约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in Entity Framework database first INSERT语句与FOREIGN KEY约束冲突-Entity Framework - The INSERT statement conflicted with the FOREIGN KEY constraint - Entity Framework INSERT语句与实体框架中的FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in Entity Framework 实体框架6-&gt;外部服务-&gt;自引用外键-&gt; INSERT语句与FOREIGN KEY约束冲突 - Entity Framework 6 -> External Service -> self referencing foreign key -> The INSERT statement conflicted with the FOREIGN KEY constraint INSERT 语句与 FOREIGN KEY SAME TABLE 约束冲突 | ASP.NET Core &amp; Entity Framework Core Code First - The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint | ASP.NET Core & Entity Framework Core Code First INSERT 语句与实体框架核心中的 FOREIGN KEY 约束冲突,单个语句中有 2 个表 - The INSERT statement conflicted with the FOREIGN KEY constraint in Entity framework core, 2 tables in single statement INSERT 语句与 FOREIGN KEY 约束冲突。 我的实体框架配置是否适合所需的行为? - The INSERT statement conflicted with the FOREIGN KEY constraint. Is My Entity Framework Configuration good for desired behaviour? 如何修复:UPDATE语句与FOREIGN KEY SAME TABLE约束冲突 - How to fix: The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM