2017-05-31 104 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