Bru*_*nri 6 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; }
}
Run Code Online (Sandbox Code Playgroud)
我想要以下数据库结构:
表公司
表总公司
表分行
我怎样才能做到这一点?
当我创建此迁移时,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
}
Run Code Online (Sandbox Code Playgroud)
你的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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用EF Core Migrations
. 该命令看起来有点像这样:
dotnet ef migrations add Initial_TPT_Migration -p ./../../ModelProject.csproj -s ./../../ModelProject.csproj -c YourContext -o ./TptModel/CodeFirst/Migrations
Run Code Online (Sandbox Code Playgroud)
它生成一个类Initial_TPT_Migration
,其中包含生成数据库的方法。
要查询,您需要将公司属性映射到字段名称。如果将此与存储库模式(链接)结合起来,它实际上可以像 EF Core 当前使用的默认方法一样方便。
YourContext ctx = ...
// Fetch all BranchOffices
var branchOffices = ctx.BranchOffices
.Select(c => new BranchOffice()
{
CompanyId = c.CompanyId,
Name = c.Company.Name,
})
.ToList();
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关此方法的更多信息。
归档时间: |
|
查看次数: |
9333 次 |
最近记录: |