Reputation: 17288
I have the following tables
Item
-------------------
ItemId (PK)
Name
Properties
-------------------
PropertyId (PK)
Name
ItemProperties
-------------------
ItemId (FK) (CPK)
PropertyId (FK) (CPK)
Value
and the following classes
class Item{
ItemId;
Name;
Properties (Collection of type ItemProperty);
}
class Property{
PropertyId;
Name;
}
class ItemProperty : Property{
Value;
}
Using EF Fluent API how do I map the above.
Upvotes: 0
Views: 328
Reputation: 364249
To make @Eranga's comment more clear. Your database is not inheritance at all it is many-to-many relationship with additional data in junction table! It is mapped this way:
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public virtual ICollection<ItemProperty> Properties { get; set; }
}
public class Property
{
public int PropertyId { get; set; }
public string Name { get; set; }
public virtual ICollection<ItemProperty> Items { get; set; }
}
public class ItemProperty
{
public int ItemId { get; set; }
public int PropertyId { get; set; }
public int Value { get; set; }
public virtual Item Item { get; set; }
public virtual Property Property { get; set; }
}
And mapping:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ItemProperty>().HasKey(ip => new { ip.ItemId, ip.PropertyId });
modelBuilder.Entity<Item>()
.HasMany(i => i.Properties)
.WithRequired(ip => ip.Item)
.HasForeignKey(ip => ip.ItemId);
modelBuilder.Entity<Property>()
.HasMany(p => p.Items)
.WithRequired(ip => ip.Property)
.HasForeignKey(ip => ip.PropertyId);
}
Upvotes: 1