Reputation: 2325
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
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