使用EF 4.1 Fluent Code First的每类型表继承

时间:2011-09-04 14:19:04

标签: entity-framework table-per-type

我有以下表格

Item
-------------------
ItemId (PK)
Name

Properties
-------------------
PropertyId (PK)
Name

ItemProperties
-------------------
ItemId (FK) (CPK)
PropertyId (FK) (CPK)
Value

以及以下课程

class Item{
     ItemId;
     Name;
     Properties (Collection of type ItemProperty);
}

class Property{
     PropertyId;
     Name;
}

class ItemProperty : Property{
     Value;
}

使用EF Fluent API如何映射上面的内容。

1 个答案:

答案 0 :(得分:1)

让@ Eranga的评论更清晰。您的数据库根本不是继承,它与联结表中的其他数据有多对多的关系!它以这种方式映射:

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; }
}

并映射:

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); 
}