实体框架v6中的TPC

时间:2017-04-26 11:13:31

标签: c# entity-framework-6 table-per-class

我正在尝试在Entity Framework中做一个非常简单的事情。

我有一个零或多个参数的产品,这些参数将映射到他们自己的表。但是,我无法让它工作。我一直在努力使映射正确,然后使用迁移来查看数据库应该是什么样子。我知道这在NHibernate中非常简单,但我不得不使用Entity Framework v6。

背景

这些是我的实体:

namespace Entities
{
    public class EntityState
    {
        public int Id { get; set; }
    }

    public class ProductState : EntityState
    {
        public virtual ICollection<ProductParameterState> Parameters { get; set; }
    }

    public abstract class ProductParameterState : EntityState
    {
    }

    public class ColorParameterState : ProductParameterState
    {
        public virtual string Color { get; set; }
    }

    public class SizeParameterState : ProductParameterState
    {
        public virtual int Size { get; set; }
    }
}

我想将其存储在以下架构中:

ERD

怎么做?

我的尝试

表每类

我尝试使用TPC进行映射:

namespace Mappings
{
    public class ProductMap : EntityTypeConfiguration<ProductState>
    {
        public ProductMap()
        {
            HasKey(x => x.Id);
            Property(x => x.Name);
            HasMany(x => x.Parameters);
        }
    }

    public class ColorParameterMap : EntityTypeConfiguration<ColorParameterState>
    {
        public ColorParameterMap()
        {
            HasKey(x => x.Id);
            Property(x => x.Color);
            Map(x =>
            {
                x.ToTable("ColorParameters");
                x.MapInheritedProperties();
            });
        }
    }

    public class SizeParameterMap : EntityTypeConfiguration<SizeParameterState>
    {
        public SizeParameterMap()
        {
            HasKey(x => x.Id);
            Property(x => x.Size);
            Map(x =>
            {
                x.ToTable("SizeParameters");
                x.MapInheritedProperties();
            });
        }
    }
}

但这会产生错误The association 'ProductState_Parameters' between entity types 'ProductState' and 'ProductParameterState' is invalid. In a TPC hierarchy independent associations are only allowed on the most derived types.

不要使用继承策略

所以我尝试删除MapInheritedProperties,但之后又要创建一个额外的,不需要的表:

CreateTable(
    "dbo.ProductParameterStates",
    c => new
        {
            Id = c.Int(nullable: false, identity: true),
            ProductState_Id = c.Int(),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.ProductStates", t => t.ProductState_Id)
    .Index(t => t.ProductState_Id);

我不想要这个。通过移除Parameters中的Product属性,我可以摆脱这一个,但后来我无法使用Parameter的{​​{1}}。< / p>

我要求的太多还是可能?

1 个答案:

答案 0 :(得分:1)

您可以使用TPC,但关系必须是双向的,并且定义了明确的FK(我猜这与错误消息中提到的“独立关联”相反)。

将反向导航属性和FK属性添加到基础实体:

public abstract class ProductParameterState : EntityState
{
    public int ProductId { get; set; }
    public ProductState Product { get; set; }
}

并使用与您第一次尝试时相同的实体配置,但ProductMap除外,您可以删除以下内容

HasMany(x => x.Parameters);

或将其更改为

HasMany(e => e.Parameters)
    .WithRequired(e => e.Product)
    .HasForeignKey(e => e.ProductId);