Entity Framework 6 0.1 to 0.1 relationship with fluent api

c# ef-fluent-api entity-framework entity-framework-6

Question

Lets say I want to model a company car pool in Entity Framwork 6:

  • I have employees and Cars.
  • An empoyee can either have a car or no car.
  • A Car can either belong to an employee or no employee.

I know how to model this in a relation database with an intermediate table:

EmployeeCarAssociation
-EmployeeId
-CarId

With EmpoyeeId and CarId as primary key and an uniqe constraint on both columns.

But how can I create this 0.1-to-0.1-relation with the EF6 Fluent Api?

1
0
4/24/2018 8:44:47 AM

Accepted Answer

Try this code:

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);
    }
}
1
4/24/2018 11:03:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow