Bobby B
Bobby B

Reputation: 2325

One-to-many using EF5 fluent API

Using EF5, I want a one-to-many mapping for Car:Wheel == 1:0..n

public class Car {
  public int ID { get; set; }
  public virtual ICollection<Wheel> Wheels { get; set; }
}

public class Wheel {
  public int ID { get; set; }
  // I don't want to define a reverse relationship here
}

So for Car I did:

modelBuilder.Entity<Car>()
  .HasMany(x => x.Wheels)
  .WithMany()
  .Map(x => x
    .MapLeftKey("CarID")
    .MapRightKey("WheelID")
    .ToTable("Car_Wheel"));

Which gives me an n:n join table. But I want 1:n.

Do I need to define a unique constraint on Car_Wheel.CarID (if so, how?), or is there an easier way?

Upvotes: 1

Views: 784

Answers (1)

Dennis
Dennis

Reputation: 37760

But I want 1:n

Use WithRequired or WithOptional:

modelBuilder
            .Entity<MyParentEntity>()
            .HasMany(_ => _.Children)
            .WithRequired() //.WithOptional()
            .Map(/* map association here */);

But it will be better, if you will use foreign key associations:

public class Wheel 
{
  public int ID { get; set; }
  public int CarID { get; set; }
}

modelBuilder
    .Entity<MyParentEntity>()
    .HasMany(_ => _.Children)
    .WithRequired() //.WithOptional()
    .HasForeignKey(_ => _.ParentId);

Upvotes: 1

Related Questions