0

Hi guys I am facing a problem in asp.net mvc.

I have two tables Users and Projects and third table which creates a many to many relation in them User_Project but when I imported the tables in visual studio there is no table of User_Project but I can access there values from navigation or like db.Users.Where(u => u.Projects.Contains(SomeUser));.

But now I just want to add the User in database who is related to some project and I am using following query but its not working.

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

Hope i explained my problem.

Unable to update the EntitySet 'User_Project' because it has a DefiningQuery and no element exists in the element to support the current operation.

I also have the primary keys in both tables Users.ID and Projects.ID and also the link in edmx file.

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

UserModel

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

Project Model

    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; }
}
Hasan Mir
  • 121
  • 1
  • 2
  • 8

1 Answers1

0

you add user 2 time because it's reference type to the same location in memory

you can do that

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

and please check if the user table has primary key

shady youssery
  • 430
  • 2
  • 17