0

大家好,我在 asp.net mvc 中遇到问题。

我有两个表UsersProjects第三个表,它们在其中创建了多对多关系,User_Project但是当我在 Visual Studio 中导入表时,没有表,User_Project但我可以从导航或类似中访问这些值db.Users.Where(u => u.Projects.Contains(SomeUser));

但现在我只想添加User与某个项目相关的数据库,我正在使用以下查询但它不起作用。

Project pro = db.Projects.Where(p => p.ID == x).FirstOrDefault();
                        pro.Users.Add(usr);
                        db.Users.Add(usr);
          error line => db.SaveChanges();    

希望我解释了我的问题。

无法更新 EntitySet 'User_Project',因为它具有 DefiningQuery 并且元素中不存在支持当前操作的元素。

Users.ID我在两个表中也有主键,Projects.ID还有 edmx 文件中的链接。

<AssociationConnector Association="BugMesh_Model.User_Project" ManuallyRouted="false" />

用户模型

    public partial class User
{
    public User()
    {
        this.Bugs = new HashSet<Bug>();
        this.Bugs1 = new HashSet<Bug>();
        this.Projects = new HashSet<Project>();
    }

    public int ID { get; set; }
    public string UserName { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }

    public virtual ICollection<Bug> Bugs { get; set; }
    public virtual ICollection<Bug> Bugs1 { get; set; }
    public virtual ICollection<Project> Projects { get; set; }
}

项目模型

    public partial class Project
{
    public Project()
    {
        this.Bugs = new HashSet<Bug>();
        this.Components = new HashSet<Component>();
        this.Users = new HashSet<User>();
    }

    public int ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Status { get; set; }
    public Nullable<System.DateTime> CreationDate { get; set; }

    public virtual ICollection<Bug> Bugs { get; set; }
    public virtual ICollection<Component> Components { get; set; }
    public virtual ICollection<User> Users { get; set; }
}
4

1 回答 1

0

您添加用户 2 次,因为它是对内存中同一位置的引用类型

你可以这样做

      pro.Users.Add(usr);
      db.SaveChanges();  

请检查用户表是否有 primary key

于 2016-08-04T14:38:33.687 回答