I have the tables that look like this
Users
- UserID (PK)
- UserName
- ...
UserSettings
- UserID (PK)
- Settings
My UserSetting entity looks like this
public class UserSetting
{
public UserSetting()
{
}
[Key]
[Column("UserID", TypeName ="nvarchar(128)")]
public string ID { get; set; }
[Required]
public string Settings { get; set; }
}
I want the PK of UserSettings to add a FK from UserID in Users to UserID in UserSettings as the relationship is supposed to be 1:1 (in case you are wondering the settings field is a string that the frontend just dumps in the database as a json string and the backend does not care about the values inside)
This works fine if I create the database by hand and add the foreign key and EF knows nothing about it but I decided to try letting EF create the DB for this project. Is there a way to tell EF to create that FK without adding entity properties for the relation to either of the entities?
To create a relationship in Code First you need to have at least a navigation property in one of both ends (this kind of relationship are called unidirectional relationships). A typical one to one relationship is configured as follow:
public class User
{
public User()
{
}
[Key]
[Column("ID", TypeName ="nvarchar(128)")]
public string ID { get; set; }
public string Name{ get; set; }
public virtual UserSetting UserSetting {get;set;}
}
public class UserSetting
{
public UserSetting()
{
}
[Key,ForeignKey("User"),Column("UserID")]
public string ID { get; set; }
//...
public virtual User User{get;set;}
}
Now, with this model you aren't adding any new column to your tables, it's going to be the same, only now you're configuring the PK of UserSettings
table as FK of the relationship (what you are trying to achieve).
Now, as I said EF needs at least one navigation property to create the relationship. So, if you want, you can delete the UserSetting
nav. property on User
, that's ok, leaving the data annotations over the Id
of UserSetting
and the User
navigation property is enough to Code First to create the relationship.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments