处理多种关系类型

时间:2014-07-14 19:47:41

标签: .net entity-framework ef-code-first

说我有这个型号:

public class Company
{
    public long Id { get; set; }

    public string Name { get; set; }

    public Employee CEO { get; set; }
    public ICollection<Employee> Employees { get; set; }

    public Company()
    {
        Employees = new HashSet<Employee>();
    }
}

public class Employee
{
    public long Id { get; set; }

    public string Name { get; set; }
}

public class CorporateContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Employee> Employees { get; set; }
}

代码:

[ClassInitialize]
public static void SetUp(TestContext _)
{
    Database.SetInitializer(new DropCreateDatabaseAlways<CorporateContext>());
}

[TestMethod]
public void CanHandleMultipleRelations()
{
    Company Disney = new Company { Name = "Disney" };

    Employee Mickey = new Employee { Name = "Mickey Mouse" };
    Employee Donald = new Employee { Name = "Donald Duck" };
    Employee Goofy = new Employee { Name = "Goofy Goof" };

    Disney.CEO = Mickey;

    Disney.Employees.Add(Mickey);
    Disney.Employees.Add(Donald);
    Disney.Employees.Add(Goofy);

    using (CorporateContext context = new CorporateContext())
    {
        context.Database.Initialize(true);
    }

    using (CorporateContext context = new CorporateContext())
    {
        context.Companies.Add(Disney);

        context.SaveChanges();
    }
}

模型没有问题,因为EF能够创建正确的数据库架构。

问题在于实体处于两种关系中,例如米奇既是CEO又是员工。

调用SaveChanges时,我收到此异常:

Additional information: An error occurred while saving entities that do not expose foreign key properties for their relationships.
The EntityEntries property will return null because a single entity cannot be identified as the source of the exception.
Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
See the InnerException for details.

内在异常:

Unable to determine a valid ordering for dependent operations.
Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

我想我理解这个问题:

  • CEO属性在Company表格中被翻译为 FK ,因此当我插入新公司时,EF需要某些Id雇员

  • Employee类映射到一个表格,其中FK指向Company表以表示1-n关系,所以当我插入一个员工时,我应该指定一个公司< / p>

所以,当我插入一家公司,其首席执行官是新员工时EF因为有一个问题而丢失22:要插入公司,它需要CEO ID,所以它需要插入CEO,但为此它需要id公司...

我试图通过明确定义FK来帮助EF:

[ForeignKey("Company_Id")]
public Company Company { get; set; }
public long? Company_Id { get; set; }

但即使所有列都可以为空,并且EF理解这一点,因为所有列都可以为空,但EF仍然不想保存它。

我想我可以做两步插入:首先是员工,然后是公司。

但是我想我会失去交易性,如果可能的话我想保持简单。

那么解决这个问题的最佳解决方法/修复方法是什么?

0 个答案:

没有答案
相关问题