4

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?

Jamie
  • 4,670
  • 5
  • 35
  • 49

1 Answers1

0

I'm no EF expert but from the Model-first approach I know that this would be mapped as a collection of Animal, you can then select Farm.Animals.OfType<Pig>()

Lazarus
  • 41,906
  • 4
  • 43
  • 54
  • Wouldn't that mean that the whole collection of Animals is loaded from the SQL Server then filtered into those which are pigs? – Jamie Dec 19 '13 at 09:41
  • (Which was what I was trying to avoid with this question... http://stackoverflow.com/questions/20663337/entity-framework-filtered-navigation-properties) – Jamie Dec 19 '13 at 09:52