实体框架6与流畅的api有0.1到0.1的关系

时间:2018-04-24 08:44:47

标签: c# entity-framework entity-framework-6 ef-fluent-api

让我们说我想在Entity Framwork 6中建模公司汽车池:

  • 我有员工和汽车。
  • 一个雇员可以有车或没有车。
  • 汽车可以属于员工,也可以不属于员工。

我知道如何在具有中间表的关系数据库中对此进行建模:

EmployeeCarAssociation
-EmployeeId
-CarId

EmpoyeeIdCarId作为主键,并在两列上使用uniqe约束。

但是如何使用EF6 Fluent Api创建0.1到0.1的关系?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

public class Employee
{
    public int Id { get; set; }
    public Car Car { get; set; }
    public int? CarId { get; set; }
}

public class Car
{
    public int Id { get; set; }
    public Employee Employee { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Car> Cars { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .HasOptional(c => c.Employee)
            .WithOptionalDependent(e => e.Car)
            .Map(config =>
            {
                config.MapKey("EmployeeId");
            });

        base.OnModelCreating(modelBuilder);
    }
}