Unable to track an entity because primary key is null

Clash Royale CLAN TAG#URR8PPP
Unable to track an entity because primary key is null
I have a User and an Organization model, and an Organization may have many users.
User
Organization
Organization
Organization model class:
Organization
public virtual ICollection<User> Users get; set;
User model
[Key]
[ForeignKey("Organization")]
public int? OrganizationId get; set;
public virtual Organization Organization get; set;
In context
modelBuilder.Entity<User>().HasKey(u => new u.Id, u.OrganizationId);
modelBuilder.Entity<Organization>().HasKey(o => new o.Id);
When I want to insert one user with null organization, I get this error
Unable to track an entity of type 'User' because primary key property 'OrganizationId' is null.
int
0
null
PKs cannot be null my friend
– IteratioN7T
Aug 12 at 8:43
Why is the
OrganizationId (FK to the Organization table) the PK of table User?? Doesn't really make any sense..... shouldn't you have a UserID as the PK for the User table, and OrganizationId would only be the FK to Organization?– marc_s
Aug 12 at 9:07
OrganizationId
User
UserID
User
OrganizationId
Your code example suggests that
User has a property named Id (which sounds like it would make a good primary key) but it is absent from your model. Did you leave out something by mistake? Please clarify which property is intended to be the primary key.– John Wu
Aug 12 at 9:27
User
Id
Modify OrganizationId int not int? , it's [key]
– M.Hassan
Aug 12 at 10:23
1 Answer
1
Firstly, you have to seperate your organization and userId like this.
If I understran as correctly,
User model
[Key]
public int Id get; set;
[ForeignKey("Organization")]
public int? OrganizationId get; set;
public virtual Organization Organization get; set;
In context (may this is a bit mistake, also should be optional I am not sure, try this :) )
modelBuilder.Entity<Organization>() // One organizatio
.HasMany(c => c.User) //has mamy users
.WithOptional(c => c.Organization) // but each user doesnt have organization
.HasForeignKey(c => c.OrganizationId) // user who have organization, has foreignnId
.WillCascadeOnDelete(false);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I think the problem is: you have defined a null-able int as your PK. Changing it to
intand using0instead ofnullmay solve your issue.– S.Akbari
Aug 12 at 8:28