【问题标题】:O.R.M. Entity Framework INSERT statement conflicted with the FOREIGN KEY constraint exception [duplicate]O.R.M.实体框架 INSERT 语句与 FOREIGN KEY 约束异常冲突 [重复]
【发布时间】:2017-01-13 02:06:33
【问题描述】:

我有以下课程

public class Employee
{ 
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
    public string PhoneNumber { get; set; }
    public Guid DepartmentId { get; set; }
    public virtual Department Department { get; set; }
    public int Deleted { get; set; }

    public bool IsDeleted()
    {
        return this.Deleted == 1 ? true : false;
    }

    public void MarkAsDeleted()
    {
        this.Deleted = 1;
    }

    public string GetFullName()
    {
        return this.FirstName + " " + this.LastName;
    }
}

public class Department
{
    public Department()
    {
        this.Employees = new List<Employee>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual List<Employee> Employees { get; set; }
    public int Deleted { get; set; }

    public bool IsDeleted()
    {
        return this.Deleted == 1 ? true : false;
    }

    public void MarkAsDeleted()
    {
        this.Deleted = 1;
    }

    public void AddEmployee(Employee employee)
    {
        this.Employees.Add(employee);
    }

    public void RemoveEmployee(Employee employee)
    {
        this.Employees.Remove(employee);
    }
}

我想创建一个一对多的关系,在我的配置中我有以下代码

 [modelBuilder.Entity<Department>()
            .HasMany(l => l.Employees).
               WithRequired(r => r.Department).
               HasForeignKey(r => r.DepartmentId);

但是会抛出异常

INSERT 语句与 FOREIGN KEY 约束 \FK_dbo.Employees_dbo.Departments_DepartmentId 冲突。冲突发生在数据库\Entities\、表\dbo.Departments\、列Id

谁能帮帮我?谢谢

【问题讨论】:

    标签: c# asp.net-mvc entity-framework orm one-to-many


    【解决方案1】:

    似乎在某些时候您试图在没有Department 的情况下保存Employee。因此关系失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多