gpt4 book ai didi

c# - 将项目添加到 EF Core 中的集合导航属性

转载 作者:行者123 更新时间:2023-11-30 22:55:35 26 4
gpt4 key购买 nike

我有一个 Project 类,其中包含一组 AppUsers

public class Project
{
public int ProjectID { get; set; }

[Required(ErrorMessage = " Please enter a project name")]
public string Name { get; set; }

[Required(ErrorMessage = " Please enter a project description")]
public string Description { get; set; }

public virtual ICollection<AppUser> ProjectManagers { get; set; }

public bool UserIsAlreadyPM(string userId)
{
foreach(AppUser user in this.ProjectManagers)
{
if(user.Id == userId)
{
return true;
}
}
return false;
}
}

我的 AppUser

public class AppUser : IdentityUser
{
//add properties here later
}

我希望能够让任何特定的 AppUser 都在多个 ProjectProjectManagers 中。我通过我的存储库方法将 AppUser 添加到任何 Project.ProjectManagers:

public void AddProjectManager(int projectID, AppUser user)
{
Project proj = context.Projects.FirstOrDefault(p => p.ProjectID == projectID);
if(proj != null)
{
proj.ProjectManagers.Add(user);
context.SaveChanges();
}
}

这在第一次将 AppUser 添加到 Project.ProjectManagers 集合时有效。但是,如果我尝试将它们添加到任何其他 Project.ProjectManagers 集合中,这将不起作用。如果将它们分配给任何后续 Project.ProjectManagers,我会收到主键错误,因为它们已经在不同项目下的数据库中。

“SqlException:违反 PRIMARY KEY 约束‘PK_AppUser’。无法在对象‘dbo.AppUser’中插入重复键。重复键值为 (xxxx)。”

最佳答案

请按如下方式编写代码:

public void AddProjectManager(int projectID, AppUser user)
{
Project proj = context.Projects.Include(p => p.ProjectManagers)
.FirstOrDefault(p => p.ProjectID == projectID);

if(!proj.ProjectManagers.Any(pm => pm.Id = user.Id)) // <-- Here check that `AppUser` already not in Project's `ProjectManagers` collection
{
AppUser appUser = context.AppUsers.FirstOrDefault(p => p.Id== user.Id);
if(appUser != null) // <-- Confirm that the `AppUser` you are trying to add to Project's `ProjectManagers` collection is already exist in database
{
proj.ProjectManagers.Add(appUser);
context.SaveChanges();
}
}
}

关于c# - 将项目添加到 EF Core 中的集合导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174363/

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