TPC mappint生成基类表

时间:2012-05-29 07:57:57

标签: entity-framework ef-code-first

我想通过代码优先实现TPC映射,我读过这篇文章: Inheritance with EF Code First: Part 3 – Table per Concrete Type (TPC)

我已经编写了如下代码。

namespace TPCTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TestContext context = new TestContext())
            {
                Manager m = new Manager();
                m.AnnualSalary = 100000;
                m.Name = "Allen";
                m.Sex = true;
                m.Id = 1;

                Worker w = new Worker();
                w.Id = 2;
                w.Name = "John";
                w.Sex = true;
                w.MonthlyPay = 5000;

                context.empSet.Add(m);
                context.empSet.Add(w);
                context.SaveChanges();
            }
        }
    }

    abstract class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Sex { get; set; }
    }

    class Manager : Employee
    {
        public decimal AnnualSalary { get; set; }
        public string Department { get; set; }
    }

    class Worker : Employee
    {
        public decimal MonthlyPay { get; set; }
    }

    class TestContext : DbContext
    {
        public DbSet<Employee> empSet { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Manager>().Map(m =>
                {
                    m.MapInheritedProperties();
                    m.ToTable("Manager");
                });

            modelBuilder.Entity<Worker>().Map(m =>
                {
                    m.MapInheritedProperties();
                    m.ToTable("Worker");
                });

            modelBuilder.Entity<Employee>().Property(e => e.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None);
        }
    }
}

但是在运行代码之后,我发现Employee表也存在于数据库中,任何人都可以提供帮助吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用EF 5.0或更高版本!

自该版本以来,该问题似乎已得到解决。使用EF 4.3.1,我可以重现行为。所以只需更新。