I'm using a data structure similar to this where type of animal is determined from a discriminator column in the table:
public class Farm {
public int Id { get; set; }
public virtual ICollection<Pig> Pigs { get; set; }
public virtual ICollection<Cow> Cows { get; set; }
}
public class Animal {
public int Id { get; set; }
public int FarmId? { get; set; }
public virtual Farm Farm { get; set; }
public string Name { get; set; }
}
public class Pig : Animal {}
public class Cow : Animal {}
Mapping:
this.Map<Pig>(m => m.Requires("Type").HasValue((int) AnimalType.Pig));
this.Map<Cow>(m => m.Requires("Type").HasValue((int) AnimalType.Cow));
But I can't seem to map the relationship between the Pigs, Cows and Farm. I've tried this from FarmMap
which gives a duplicate column mapping error:
this.HasMany(t => t.Pigs)
.WithOptional(t => t.Farm)
.Map(m => m.MapKey("FarmId"));
this.HasMany(t => t.Cows)
.WithOptional(t => t.Farm)
.Map(m => m.MapKey("FarmId"));
Mapping from each of the animals doesn't work either, it generates extra columns (eg. Farm_Id
and Farm_Id1
- in addition to FarmId
- one for each animal type).
this.HasOptional(t => t.Farm)
.WithMany(t => t.Pigs)
.HasForeignKey(d => d.FarmId)
Moving the navigation property from the Animal
model to the inheriting models causes a single additional column to be generated - FarmId1
(so a little closer to what I want than the above 2!)
Is there any way to achieve this?