gpt4 book ai didi

c# - 如果 EF Core 5 以多对多关系播种数据

转载 作者:行者123 更新时间:2023-12-04 16:38:16 26 4
gpt4 key购买 nike

我有用户实体

public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }

public ICollection<Technology> Technologies { get; set; } = new List<Technology>();
}
我有技术实体
public class Technology
{
public int TechnologyId { get; set; }
public string TitleTechnology { get; set; }
public int GroupId { get; set; }
public Group Group { get; set; }
public ICollection<User> Users { get; set; } = new List<User>();
}
我想创建多对多关系,所以我有这样的 OnModelCreating方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var groupList = new List<Group>
{
new Group {GroupId = 1, TitleGroup = ".NET"}
};

var technologyList = new List<Technology>
{
new Technology {TechnologyId = 1, GroupId = 1, TitleTechnology = ".NET 5"},
new Technology {TechnologyId = 2, GroupId = 1, TitleTechnology = ".NET Framework 4.8"},
new Technology {TechnologyId = 3, GroupId = 1, TitleTechnology = "EF 6"},
new Technology {TechnologyId = 4, GroupId = 1, TitleTechnology = "ASP.NET MVC 5"}
};

var userList = new List<User>
{
new User
{
UserId = 1, FirstName = "Serhii", LastName = "Yurko", Email = "test", Password = "test",
Technologies = new List<Technology> {technologyList[0], technologyList[1]}
}
};

modelBuilder.Entity<Technology>().HasOne(exp => exp.Group).WithMany(exp => exp.Technologies).HasForeignKey(exp => exp.GroupId);
modelBuilder.Entity<User>().HasMany(p => p.Technologies).WithMany(p => p.Users)
.UsingEntity(j => j.ToTable("UserTechnology"));

modelBuilder.Entity<User>().HasData(userList);
modelBuilder.Entity<Group>().HasData(groupList);
modelBuilder.Entity<Technology>().HasData(technologyList);
base.OnModelCreating(modelBuilder);
}
当我想创建迁移时,我收到这样的异常 -

The seed entity for entity type 'User' cannot be added because it hasthe navigation 'Technologies' set. To seed relationships, add theentity seed to 'TechnologyUser (Dictionary<string, object>)' andspecify the foreign key values {'UsersUserId'}. Consider using'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see theinvolved property values.


如何建立适当的关系?

最佳答案

在 EF-core 中,您不能直接为导航属性设置种子。您必须删除该行 Technologies = ...来自 User初始化。
如所述 here ,连接表可以通过自己的 HasData 播种通过扩展 UsingEntity() 调用像这样调用:

.UsingEntity(j => j
.ToTable("UserTechnology")
.HasData(new[]
{
{ UsersID = 1, TechnologiesID = 1 },
{ UsersID = 1, TechnologiesID = 2 }
}
));
如您所见,隐藏的连接实体由与表字段具有相同属性名称(+ 类型)的匿名类型填充。这需要您了解这些外键字段的命名约定(我希望我猜对了)。
documentation 中所述,您可以通过使用相当笨重的联结表的完全初始化来掌握这一切。和 this Stack Overflow answer .这允许您强制执行自己的 FK 属性名称并在种子代码中相应地使用它们。

关于c# - 如果 EF Core 5 以多对多关系播种数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66081011/

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