这些是我的模型:
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/