0

I'm pretty new to Entity Framework as a FE Dev doing hobby stuff in my spare time. I'm trying to setup a many to many relationship with the following two classes. I want to have a table with all the users of the application. Each user can have multiple DuBists. In each DuBist there can participate multiple Users but only one User can be the active User. So I try like this (and many other things but that seams most logical to me):

public class DuBist : EntityData
{
    public string Title { get; set; }
    public virtual User ActiveUser { get; set; }
    public int ChangeCount { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

public class User : EntityData
{
    public string UserId { get; set; }
    public string Name { get; set; }
    public string ImageRef { get; set; }

    [JsonIgnore]
    public virtual ICollection<DuBist> DuBists { get; set; }
}

When I add a new DuBist I get this exception:

SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.Users'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (0).

Mock Data, so one of the users has the id "0".

Looks like I don't know enough to google what is wrong here, any help is appreciated a lot =)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jan
  • 11
  • 1
  • The exception you are seeing indicates that the primary key for Users is not set to auto-increment. In your .edmx file, click on the primary key for the Users table. In the properties view, change the 'StoreGeneratedPattern' field to 'Identity'. – Luke Caswell Samuel Sep 20 '17 at 13:44
  • Hey Luke, the id's are generated in the FE as GUIDs. And why would adding an entry to the dubist table generate a new user?! – Jan Sep 20 '17 at 13:47
  • If `ActiveUser` is set and is not a reference to an existing `User` it will definitely add that user to the Users table. Is the key value given by the exception the key of the `ActiveUser` for the `DuBist` you are inserting? – Luke Caswell Samuel Sep 20 '17 at 13:51
  • Thank you very much! Your comment lead me to get the actual reference in the api, mapping what's comming from the FE to the actual BE Object (the active user and each User in the List). But that seams very redundant to me. What would I need to do to not have to do this? The FE Object only has the fields I need there (Id, userId, Name, ImageRef) – Jan Sep 20 '17 at 14:16
  • Your `DuBist` class should contain a property that is the `UserId` of the active user. Just set that property to the `UserId` you obtained from the front end and call `SaveChanges()`, that should update the `User` property with a reference from the Users table. – Luke Caswell Samuel Sep 20 '17 at 16:16

0 Answers0