Unable to set User FK in another model (User extends IdentityUser)
I am attempting to establish relationships between my models. For context I'm using EntityFrameworkCore and Identity.
I have a User model (extends IdentityUser) and a Study model.
Studies should have one User, and Users can have multiple Studies.
The first time I tried to establish the relationships I wrote them in the models, like so:
That resulted in the warning
The foreign key property 'Study.UserId1' was created in shadow state because a conflicting property with the simple name 'UserId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type.
I am now trying to use OnModelCreating to create the relationships in DBContext
instead, like so:
However this says that IdentityUser does not contain a definition for Study and no accessible extension method 'Study' accepting a first argument of type 'IdentityUser' could be found
I have henceforth changed public IdentityUser? User { get; set; }
to public User? User { get; set; }
with the same result.
However User should contain a list of Study
objects...3 Replies
I'm fairly new to C# and ASPNET so I'm not sure where I've made any mistakes. I've been quite confused with how Identity and IdentityUser work in general; for instance I notice that a AspNetUser table is created in my database instead of a User table when migrating.
Any guidance would be sorely appreciated!
I think I've spotted where I've went wrong;
.WithMany(u => u.Study)
might have to be .WithMany(u => u.Studies)
instead. That syntax sure is confusing.Generally, you don't even necessarily need to configure it
EF will pick up on that
FooId
is an FK to Foo
And on the many-to-one relationshipHm, I was definitely getting warnings previously before I correctly implemented OnModelCreating to configure the relationships. I also thought that it didn't need configuring and was unsure why I was getting the warnings. I don't know if that was because
User
extends IdentityUser
, which could possibly affect the Ids
somehow? Previously, the Id
property didn't exist for Study, and instead it seemed to be replaced by UserId
, with an additional UserId1
created. In any case, the problem seems to be resolved for now.