【问题标题】:Entity Framework Adds existing foreign key实体框架添加现有的外键
【发布时间】:2014-02-11 17:29:44
【问题描述】:

我在使用 Entity Framework 建立关系以按照我希望的方式工作时遇到问题。情况如下。

一家商店有多个部门;食物、饮料、娱乐等。

有许多员工在一家商店工作。员工可以在一个或多个部门工作。

我的课程是:

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<EmployeeDeparmentMapping> DeparmentMappings { get; set; }
}

public class EmployeeDeparmentMapping
{
    public int Id { get; set; }
    public Employee Employee { get; set; }
    public Department Department { get; set; }

}

我首先使用代码,我的模型构建器看起来像这样

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Employee>().HasMany(e => e.DeparmentMappings).WithRequired(e => e.Employee);

        modelBuilder.Entity<EmployeeDeparmentMapping>().HasRequired(edm => edm.Department);
    }

当我尝试添加 EmployeeDeparmentMappings 时遇到问题,如下所示:

public void SomeMethod(EmployeeDeparmentMapping edm)
{
    MyDbContext myDb = new MyDbContext();
    myDb.EmployeeDepartmentMappings.Add(emd);
    myDb.SaveChanges();
}

抛出的异常是 Department 表上的 PRIMARY KEY 冲突,这是因为 EmployeeDepartmentMappings 对象中的部门可能已经存在于数据库中但不存在于 DbContext 中。

我尝试了以下方法:

public void SomeMethod(EmployeeDeparmentMapping edm)
{
    MyDbContext myDb = new MyDbContext();
    myDb.Departments.Attach(emd.Department);
    myDb.EmployeeDepartmentMappings.Add(emd);
    myDb.SaveChanges();

}

但这会引发InvalidOperationException,更改会保存到数据库,但上下文显然已损坏。

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.

我在这里做错了什么??

【问题讨论】:

  • 您能发布来自InvalidOperationException 的完整错误消息吗?
  • 现在没有太多时间解释了,但尝试将EmployeeDeparmentMapping中的EmployeeDepartment虚拟化。
  • @nintendojunkie,感谢添加到问题中。

标签: c# sql entity-framework foreign-keys


【解决方案1】:

试试:

public virtual ICollection<EmployeeDeparmentMapping> DeparmentMappings { get; set; }

public virtual Employee Employee { get; set; }
public virtual Department Department { get; set; }

虚拟,因为它们只是用于导航目的,它们已经存在

【讨论】:

  • 将它们更改为虚拟似乎没有效果,同样的问题仍然出现:(
猜你喜欢
  • 2018-08-14
  • 2020-07-24
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多