1

我想通过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表,任何人都可以帮忙吗?

提前致谢!

4

1 回答 1

0

使用 EF 5.0 或更高版本!

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

于 2014-10-04T16:24:09.277 回答