Turbofant
Turbofant

Reputation: 531

Entity Framework 6 0.1 to 0.1 relationship with fluent api

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

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?

Upvotes: 0

Views: 390

Answers (1)

OJ Raqueño
OJ Raqueño

Reputation: 4561

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);
    }
}

Upvotes: 1

Related Questions