I have User which may have zero or one Profile.
From the code perspective it should be more convenient if I can access Profile from User (because I will access User information more often then its profile), but this conflicts with EF Code First:
class User
{
public int Id { get; set; }
[ForeignKey("Id")]
public virtual Profile Profile { get; set; }
}
class Profile
{
public int Id { get; set; }
}
This, put in DbContext, will create tables, where I cannot create User without having Profile created before => bad, as the User is obvious principle.
The easiest (for stupid I) solution is obvious:
class User
{
public int Id { get; set; }
}
class Profile
{
public int Id { get; set; }
[ForeignKey("Id")]
public virtual User User { get; set; }
}
This gives me more expected behaviour of databases.
But… I have feeling that this solution is not best approach. For example I’m not able to access all Users through all Profiles using lazy loading.
So the question is “How to properly setup one-to-zero/one relationship (via DataAnnotation and FluentAPI)?”
In other words “How to properly setup “one User – to – zero/one Profile” relationship?”
Maybe I think of it totally wrong…
Thanks to Drauka. His proposal led me to the solution:
So the trick is done by
Requiredwhich marks that the entity, where it is defined, is dependent while the other one is principal. And it saves one collumn in both tables (for foreign key id).Just one problem remained: how to ensure
Profileis deleted in cascade when deletingUser?