【问题标题】:Adding item to collection navigation property in EF Core将项目添加到 EF Core 中的集合导航属性
【发布时间】:2019-08-06 01:07:39
【问题描述】:

我有一个 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)。”

【问题讨论】:

  • 你在使用实体框架吗?
  • @John 是的,我正在使用 EF 和 Core 2.1
  • @coolhand 将您的 AppUser 模型类添加到问题中。
  • @TanvirArjel 我已编辑问题以添加 AppUser
  • @coolhand 您添加的内容没有任何好处。也添加 AppUser 类所有属性。

标签: c# asp.net-core model-view-controller entity-framework-core


【解决方案1】:

请按如下方式编写代码:

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

【讨论】:

  • 一旦我重构了我的存储库,它就起作用了。但是,在调用 AddProjectManager() 之前,我的控制器中已经对 AppUser 进行了额外检查
猜你喜欢
  • 1970-01-01
  • 2022-10-19
  • 2018-02-03
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
相关资源
最近更新 更多