2017-05-31 106 views
0

多个对象我在SQL Server中一个奇怪的遗留表,我不知道我是否可以使用以下逻辑:实体框架|从一个表

Table [PartiesTable] 
- Id 
- FirstName 
- LastName 
- Name 
- Type 

与以下类:

public abstract class Party { 
    public Guid Id { get; set; } 
} 

public class Person : Party { 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

public class Company : Party { 
    public string Name { get; set; } 
} 

,这是一个例如记录

╔════╦═════════════╦══════════╦═══════╦══════╗ 
║ id ║ FirstName ║ LastName ║ Name ║ Type ║ 
╠════╬═════════════╬══════════╬═══════╬══════╣ 
║ 1 ║ John  ║ Kenedy ║ NULL ║ P ║ 
╠════╬═════════════╬══════════╬═══════╬══════╣ 
║ 2 ║ Meresa  ║ Oslo  ║ NULL ║ P ║ 
╠════╬═════════════╬══════════╬═══════╬══════╣ 
║ 3 ║ NULL  ║ NULL  ║ ACME ║ C ║ 
╚════╩═════════════╩══════════╩═══════╩══════╝ 

我试图按照这里的文档(https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application),但它们指的是一个例子,你有3 TABL es,我没有

回答

2

这实际上是EF代码中的默认行为。只需简单地定义您的类,将其全部映射到名为PartiesTable的表并设置鉴别器列。配置应该看起来像这样:

modelBuilder.Entity<Party>() 
      .Map<Person>(m => { m.Requires("Type").HasValue("P"); m.ToTable("PartiesTable");}) 
      .Map<Company>(m => { m.Requires("Type").HasValue("C"); m.ToTable("PartiesTable"); }) 
      .ToTable("PartiesTable"); 
+0

@ akos-nagy的现货,谢谢 – Raffaeu