我与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的示例解决方案。
我现在可以看到您的问题。如果address
具有指向address_country
的外键,则意味着一个AddressDto
只能具有一个CountryLocaleDto
。如果您希望一个address
连接到鬃毛address_country
,则在您的address_country中,您应该具有一个address
如果要建立多对多关系,则需要一个中介表address_country_address
如果使用第一个解决方案,则可以在AddressId
中添加address_country
列,并像这样扩展CountryLocaleDto
:
public class CountryLocaleDto
{
public int Id { get; set; }
public string Locale { get; set; }
public int AddressId {get; set;}
}
然后执行以下操作?
modelBuilder.Entity<AddressDto>()
.HasMany(c => c.CountryLocaleDto)
.WithOne(e => e.AddressDto);
.HasForeignKey(x => x.CountryId);
这通常是我们向多个CountryLocale声明一个地址的方式。
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; }
public int AddressDtoId {get; set;}
public AddressDto Address {get; set;}
}
modelBuilder.Entity<CountryLocaleDto>()
.HasOne(p => p.Address)
.WithMany(b => b.CountryLocale);
这应该配置一对多的关系,并向多个国家/地区分配一个地址。
此来源为:https://docs.microsoft.com/en-us/ef/core/modeling/relationships#fluent-api
同样,您可以执行类似的操作,并从CountryLocaleDto中删除AddressDto属性:
modelBuilder.Entity<CountryLocaleDto>(model =>
{
model.HasOne<AddressDto>()
.WithMany()
.HasForeignKey(x => x.AddressDtoId);
});
UPDATE:
modelBuilder.Entity<AddressDto>()
.HasMany(b => b.CountryLocale)
.WithOne();
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; }
}
来源:https://docs.microsoft.com/en-us/ef/core/modeling/relationships-单个导航属性