【发布时间】: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 位于多个Project 的ProjectManagers 内。我通过我的存储库方法将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