2

请看下面的代码。

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

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

4

1 回答 1

2

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

于 2012-05-21T07:54:32.263 回答