Entity framework 首先使用EF 4.1 Fluent代码的表每类型继承

Entity framework 首先使用EF 4.1 Fluent代码的表每类型继承,entity-framework,table-per-type,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 (Coll

我有下列表格

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如何映射上述内容。

以使@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; }
}
公共类项目
{
公共int ItemId{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection属性{get;set;}
}
公共类财产
{
公共int属性ID{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection项{get;set;}
}
公共类ItemProperty
{
公共int ItemId{get;set;}
公共int属性ID{get;set;}
公共int值{get;set;}
公共虚拟项项{get;set;}
公共虚拟财产属性{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); 
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasKey(ip=>new{ip.ItemId,ip.PropertyId});
modelBuilder.Entity()
.HasMany(i=>i.Properties)
.WithRequired(ip=>ip.Item)
.HasForeignKey(ip=>ip.ItemId);
modelBuilder.Entity()
.HasMany(p=>p.Items)
.WithRequired(ip=>ip.Property)
.HasForeignKey(ip=>ip.PropertyId);
}

您的型号不适合
TPT
,因为
ItemProperties
PK与
Properties
PK不同。