实体框架ALTER TABLE语句与FOREIGN KEY约束冲突 [英] Entity Framework The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

查看:119
本文介绍了实体框架ALTER TABLE语句与FOREIGN KEY约束冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Entity Framework中进行数据库更新时,首先进行代码迁移,我遇到此错误:

On updating database in Entity Framework , Code first Migration, I am getting this error:


ALTER TABLE语句与FOREIGN冲突密钥约束 FK_dbo.Clients_dbo.MedicalGroups_MedicalGroupId。冲突发生在数据库 hrbc的表 dbo.MedicalGroups的列 Id中。

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Clients_dbo.MedicalGroups_MedicalGroupId". The conflict occurred in database "hrbc", table "dbo.MedicalGroups", column 'Id'.

这是我的课程:

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; } }
}

这是我的第二堂课:

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");
}


推荐答案

我得到了我的解决方案问题。问题是我的客户表中有数据。因为我的客户表具有不实际存在的medicalgroupid值,所以它给我外键约束错误。

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.

Update Client set MedicalGroupId = NULL

这篇关于实体框架ALTER TABLE语句与FOREIGN KEY约束冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆