EF Core 5 多对多关系 - 更改导航键
EF Core 5 Many-to-Many relation - Change the Navigation key
我有两个在 EF Core 5 中具有多对多关系的实体,我正在使用流利的 API 来设置关系。
public class Framework
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string Name { get; set; }
public IList<Path> Paths { get; set; } = new List<Path>();
}
public class Path
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string Name { get; set; }
public IList<Framework> Frameworks { get; set; } = new List<Framework>();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Framework>()
.HasMany(x => x.Paths)
.WithMany(x => x.Frameworks)
.UsingEntity<Dictionary<string, object>>(
"FrameworkPaths",
x => x.HasOne<Path>().WithMany(),
x => x.HasOne<Framework>().WithMany(),
);
工作正常,正在多对多 table 中添加数据(其中包含这些列 FrameworksId、PathsId)
但现在我想将 Path 实体中的 属性 名称从 Frameworks 更改为 LinkedFrameworks 作为
public IList<Framework> LinkedFrameworks { get; set; } = new List<Framework>();
如何在实体的 CRUD 操作中使用这个新的 属性 名称 LinkedFrameworks 而不是 Framework?
通过在usingEntity中添加.HasForeignKey()实现
builder.Entity<Framework>()
.HasMany(x => x.Paths)
.WithMany(x => x.LinkedFrameworks) //Change the name here
.UsingEntity<Dictionary<string, object>>(
"FrameworkPaths",
x => x.HasOne<Path>().WithMany(),
x => x.HasOne<Framework>().WithMany().HasForeignKey("FrameworksId")); //tell the EF about the Foreign Key
我有两个在 EF Core 5 中具有多对多关系的实体,我正在使用流利的 API 来设置关系。
public class Framework
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string Name { get; set; }
public IList<Path> Paths { get; set; } = new List<Path>();
}
public class Path
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string Name { get; set; }
public IList<Framework> Frameworks { get; set; } = new List<Framework>();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Framework>()
.HasMany(x => x.Paths)
.WithMany(x => x.Frameworks)
.UsingEntity<Dictionary<string, object>>(
"FrameworkPaths",
x => x.HasOne<Path>().WithMany(),
x => x.HasOne<Framework>().WithMany(),
);
工作正常,正在多对多 table 中添加数据(其中包含这些列 FrameworksId、PathsId)
但现在我想将 Path 实体中的 属性 名称从 Frameworks 更改为 LinkedFrameworks 作为
public IList<Framework> LinkedFrameworks { get; set; } = new List<Framework>();
如何在实体的 CRUD 操作中使用这个新的 属性 名称 LinkedFrameworks 而不是 Framework?
通过在usingEntity中添加.HasForeignKey()实现
builder.Entity<Framework>()
.HasMany(x => x.Paths)
.WithMany(x => x.LinkedFrameworks) //Change the name here
.UsingEntity<Dictionary<string, object>>(
"FrameworkPaths",
x => x.HasOne<Path>().WithMany(),
x => x.HasOne<Framework>().WithMany().HasForeignKey("FrameworksId")); //tell the EF about the Foreign Key