代码首先使用抽象类,fk无法生成

时间:2012-05-21 06:41:40

标签: entity-framework inheritance ef-code-first abstract-class

请查看下面的代码。

class Program
{
    static void Main(string[] args)
    {
        using (myContext context = new myContext())
        {
            Team t = new Team();
            t.id = 1;
            t.Name = "asd";
            context.teamSet.Add(t);
            context.SaveChanges();
        }
    }
}

public abstract class Base
{
    public virtual int id { get; set; }
}

public abstract class Player : Base
{
    public virtual string Name { get; set; }
    public virtual int Number { get; set; }
    public virtual Team team { get; set; }
    [ForeignKey("team")]
    public int teamId { get; set; }
}

public class Team : Base
{
    public ICollection<Player> Players { get; set; }
    public string Name { get; set; }
}

public class FootballPlayer : Player
{
    public double Speed { get; set; }
}

public class BasketballPlayer : Player
{
    public double Height { get; set; }
    public double Speed { get; set; }
}

public class myContext : DbContext
{
    public DbSet<Player> playerSet { get; set; }
    public DbSet<Team> teamSet { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new BaseConfiguration()).Add(new PlayerConfiguration()).Add(new TeamConfiguration()).Add(new FootballConfiguration()).Add(new BasketballConfiguration());           
    }
}

public class BaseConfiguration : EntityTypeConfiguration<Base>
{
    public BaseConfiguration()
    {
        HasKey(k => k.id);
        Property(p => p.id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

public class PlayerConfiguration : EntityTypeConfiguration<Player>
{ 
    public PlayerConfiguration()
    {
        Map(p=>{
            p.MapInheritedProperties();
        p.ToTable("Player");
        });
    }
}

public class TeamConfiguration : EntityTypeConfiguration<Team>
{
    public TeamConfiguration()
    {
        Map(p =>
        {
            p.MapInheritedProperties();
            p.ToTable("Team");
        });
    }
}

public class FootballConfiguration : EntityTypeConfiguration<FootballPlayer>
{
    public FootballConfiguration()
    {
        ToTable("FootballPlayer");
    }
}

public class BasketballConfiguration : EntityTypeConfiguration<BasketballPlayer>
{
    public BasketballConfiguration()
    {
        ToTable("BasketballPlayer");
    }
}

我的Player类和Team Class派生自Based Class,而FootballPlayer和BasketballPlayer派生自Player。但是在生成的数据库中,Player表不包含FK teamId,它只是一个公共属性。此外,FootballPlayer和BasketballPlayer表不包含从Player类派生的属性。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您想要实现什么继承映射?目前,BasePlayer之间的TPC和Player及其派生类型之间的TPT。如果要在这些派生类型中具有继承属性,则必须使用TPC,但在这种情况下,数据库中不应有Player表。要将TPC用于播放器,您必须在其映射配置中使用MapInheritedProperties