简体   繁体   English

实体框架| 一个表中的多个对象

[英]Entity Framework | Multiple Objects from one table

I have a strange legacy Table in SQL Server and I wonder if I can use the following logic: 我在SQL Server中有一个奇怪的旧表,我想知道是否可以使用以下逻辑:

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

And the following classes: 和以下类:

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; }
}

And this is an example of the records 这是记录的一个例子

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

I tried to follow the docs here ( 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 ) but they refer to an example where you have 3 tables, which I do not have 我试图按照此处的文档进行操作( https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-在一个ASP.NET MVC应用程序中的实体框架 ),但它们引用的示例中有3个表,而我没有

This is actually the default behavior in EF code first. 实际上,这实际上是EF代码中的默认行为。 Just simply define your classes, map all of them to the table named PartiesTable and set the discriminator column. 只需定义您的类,将所有类映射到名为PartysTable的表并设置“ discriminator”列即可。 The configuration should look something like this: 配置应如下所示:

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM