Search code examples
c#entity-frameworkentity-framework-6ef-fluent-api

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 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?


Solution

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