这些是我的模型:
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; } }我想要以下数据库结构:
I wanted the following database structure:
表公司
- CompanyId(PK)
- 名称
- 地址
- 电子邮件
- 网址
- CompanyId (PK)
- Name
- Address
- Url
表HeadOffice
- HeadOfficeId(PK)
- CompanyId(FK)
表BranchOffice
- BranchOfficeId(PK)
- HeadOfficeId(FK)
- CompanyId(FK )
我该怎么做?
我创建此迁移时,EF仅创建一个包含所有列的表!我不需要这种方法!
When I create this migration, the EF creates just one table, with all columns! I don't want this approach!
推荐答案您必须将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.
更多推荐
Entity Framework Core 2.0中每种类型的表
发布评论