c# - Entity Framework Core 2.0 中每种类型的表

标签 c# entity-framework entity-framework-core

这些是我的模型:

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

我想要以下数据库结构:

表公司

  • 公司编号(PK)
  • 姓名
  • 地址
  • 电子邮件
  • 网址

表总部

  • 总部编号 (PK)
  • CompanyId (FK)

Table BranchOffice

  • BranchOfficeId (PK)
  • 总部编号 (FK)
  • CompanyId (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
}

您的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 迁移。该命令看起来有点像这样:

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

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

用法

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

YourContext ctx = ...

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

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

关于c# - Entity Framework Core 2.0 中每种类型的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733184/

相关文章:

c# - 索引器通过引用获取还是获取+设置?

c# - C# Datagrid 的 WHERE 子句的文本框

javascript - 如果使用单个实体,使用自动映射器对我来说效果很好

c# - 尝试使用 Entity Framework 和迁移创建数据库时出现问题

c# - 渲染 WPF 网络 map /图形布局 - 手动?路径列表框?还有什么?

c# - 引用文件

.net - 将 ObjectContext 存储在 ASP.NET 中的线程静态变量中是否安全?

c# - 如何删除 Entity Framework Core 2.0 中的特定迁移?

c# - DbUpdateException - 当我捕获所有异常时重复键错误未处理

entity-framework-core - 包管理器控制台添加迁移命令不起作用