与EF Core建立一对多关系时遇到问题。
我有两个表address
和address_country
。有模式:
如您所见,我想存储具有不同语言环境的国家。因此它具有组合键。 address
表具有address_country
的外键。不幸的是,我无法设置ContextDb
来实现自己想要的功能。 Address
模型中未填写国家/地区列表。
我在Context
中有以下代码:
public class Context : DbContext
{
protected override void Onconfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(
@"Data Source=addresses.db");
base.Onconfiguring(optionsBuilder);
}
protected override void OnmodelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AddressDto>()
.ToTable("address");
modelBuilder.Entity<CountryLocaleDto>()
.ToTable("address_country");
modelBuilder.Entity<CountryLocaleDto>()
.HasKey(cl => new {cl.Id,cl.Locale});
base.OnmodelCreating(modelBuilder);
}
public DbSet<AddressDto> Addresses { get; set; }
}
我的模特是
public class AddressDto
{
public int Id { get; set; }
public int CountryId { get; set; }
public List<CountryLocaleDto> CountryLocale { get; set; }
}
public class CountryLocaleDto
{
public int Id { get; set; }
public string Locale { get; set; }
}
也不例外。我根本不知道如何配置这种关系。有人可以帮我吗?
示例数据为:
地址(id,countryId)
(1,1)
(2,1)
address_country(ID,语言环境,名称)
(1,'en','Germany')
(1,'de','Deutschland')
使用this link可以找到SQLite db的示例解决方案。