且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Entity Framework Core 2.0中每种类型的表

更新时间:2022-01-17 00:41:59

您必须将Model更改为如下所示,请注意,您可以'

You would have to change your Model to look like this, note that you can't use inheritance using this approach:

public class Company
{
   public int CompanyId { get; set; }
   //...
}

public class Company
{
   public int CompanyId { get; set; }
   public string Name { get; set; }
   //...
}

public class HeadOffice
{
   [ForeignKey(nameof(Company))]
   public int CompanyId { get; set; }
   public Company Company { get; set; }
   // Add Properties here
}

public class BranchOffice
{
   [ForeignKey(nameof(Company))]
   public int CompanyId { get; set; }
   public Company Company { get; set; }
   // Add Properties here
}

您的 DbContext

public class YourContext : DbContext
{
  public DbSet<Company> Companys { get; set; }
  public DbSet<HeadOffice> HeadOffices { get; set; }
  public DbSet<BranchOffice> BranchOffices { get; set; }

  public YourContext(DbContextOptions<YourContext> options)
    : base(options)
  {
  }
}

然后可以使用 EF核心迁移。该命令看起来像这样:

You could then use EF Core Migrations. The command would look somewhat like this:

dotnet ef migrations add Initial_TPT_Migration -p ./../../ModelProject.csproj -s ./../../ModelProject.csproj -c YourContext -o ./TptModel/CodeFirst/Migrations

它生成一个类 Initial_TPT_Migration 包含用于生成数据库的方法。

It generats a Class Initial_TPT_Migration that contains methods to generate your database.

要查询,您需要将公司属性映射到字段名称。如果将其与存储库模式链接),它实际上可能与当前使用EF Core中的默认方法一样方便。

To query you would need to map Company Properties to the fieldnames. If you combine this with the Repository Pattern (link), it could actually be as convenient as the default approach in EF Core currently is to use.

YourContext ctx = ...

// Fetch all BranchOffices
var branchOffices = ctx.BranchOffices
          .Select(c => new BranchOffice()
                  {
                    CompanyId = c.CompanyId,
                    Name = c.Company.Name,
                  })
          .ToList();

您可以找到有关此方法的更多信息此处

You can find more informations about this approach here.