Entity Framework Core 2.0 中每种类型的表

2024-04-22

这些是我的模型:

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

public class HeadOffice : Company
{
   public int HeadOfficeId { get; set; }
   public virtual List<BranchOffice> BranchOffice { get; set; } = new List<BranchOffice>();
}

public class BranchOffice : Company
{
   public int BranchOfficeId { get; set; }
   public virtual HeadOffice HeadOffice { get; set; }
}

我想要以下数据库结构:

表公司

  • 公司 ID (PK)
  • Name
  • Address
  • Email
  • Url

表总公司

  • 总部 ID (PK)
  • 公司 ID (FK)

表 分支机构

  • 分支机构 ID (PK)
  • 总部 ID (FK)
  • 公司 ID (FK)

我怎样才能做到这一点?

当我创建此迁移时,EF 仅创建一张包含所有列的表!我不想要这种方法!


您必须将模型更改为如下所示,请注意,您不能使用这种方法来使用继承:

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
}

Your 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 Core Migrations。该命令看起来有点像这样:

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

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

Usage

要查询,您需要将公司属性映射到字段名称。如果你把它与存储库模式 (link https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application),它实际上可以像 EF Core 当前使用的默认方法一样方便。

YourContext ctx = ...

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

您可以找到有关此方法的更多信息here https://weblogs.thinktecture.com/pawel/2018/05/entity-framework-core-inheritance-tpt-is-not-supported-is-it-part-1-code-first.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Entity Framework Core 2.0 中每种类型的表 的相关文章

随机推荐