我在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://learn.microsoft.com/en-us/aspnet/mvc/mvc/overview/getting-started/getting-started-with-with-with-ef-ef-usis-mvc/implementing-inheritance-inheritance-inheritance-inheritance - 与实体 - 框架中的An-As-Asp-net-mvc-application(一起,但它们是指您有3个表的示例,我没有3个表,我没有
这实际上是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");