gpt4 book ai didi

c# - 与具有多行的 fk 建立一对多关系

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:31 24 4
gpt4 key购买 nike

我在设置与 EF Core 的一对多关系时遇到问题。
我有两个表 addressaddress_country .有模式: address table schema
address_country table schema
如您所见,我想存储具有不同语言环境的国家/地区。所以它有一个组合键。 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; }
}

也不异常(exception)。我根本不知道如何配置这种关系。有人可以帮我吗?

示例数据为:
地址

<表类="s-表"><头>id国家/地区编号<正文>1121

地址国家

<表类="s-表"><头>id语言环境名字<正文>1'zh''德国'1'的''德国'

使用 SQLite 数据库的示例解决方案可以在 this link 中找到.

最佳答案

如果我没看错 - 你只需要将这段代码添加到你的上下文类中

modelBuilder.Entity<AddressDto>()
.HasMany(e=>e.CountryLocale)
.WithOne()
.HasForeignKey(x=>x.Id)
.HasPrincipalKey(x=>x.CountryId);

在这里你必须添加HasForeignKeyHasPrincipalKey

Entity Framework Core Fluent API HasForeignKey 方法用于指定哪个属性是关系中的外键。

主键:唯一标识主体实体的属性。这可能是主键或备用键。 导航属性:在包含对相关实体的引用的主体和/或依赖实体上定义的属性。

你的模型应该是这样的

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; }
}

我的意思是您不必在模型中添加任何其他内容。

希望对您有所帮助。

附言感谢添加示例项目

关于c# - 与具有多行的 fk 建立一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com