I have a problem with setting up a one-to-many relation with EF Core.
I have two tables address
and address_country
. There are schemas:
As you see, I want to store countries with different locales. So it has a composed key. address
table has a foreign key to address_country
. Unfortunately, I cannot setup ContextDb
to achieve what I want. The list of countries is not filled in Address
model.
I have the following code in 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; }
}
也不例外。我根本不知道如何配置这种关系。有人可以帮我吗?
示例数据如下:
address
地址_国家
id |
locale |
name |
1 |
'en' |
'Germany' |
1 |
'de' |
'Deutschland' |
可以通过以下方式找到 SQLite db 的示例解决方案这个链接 https://github.com/VitaliiIsaenko/ef-core-example-relation.
如果我没猜错的话 - 你只需要将这段代码添加到你的上下文类中
modelBuilder.Entity<AddressDto>()
.HasMany(e=>e.CountryLocale)
.WithOne()
.HasForeignKey(x=>x.Id)
.HasPrincipalKey(x=>x.CountryId);
这里你必须添加有外键 and 拥有主密钥
实体框架核心 Fluent API有外键方法用于指定哪个属性是关系中的外键。
主密钥:唯一标识主要实体的属性。这可能是主键或备用键。导航属性:在主体和/或依赖实体上定义的属性,包含对相关实体的引用。
你的模型应该是这样的
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; }
}
我的意思是您不必在模型中添加任何其他内容。
我希望这有帮助。
附:感谢添加示例项目
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)