Reputation: 853
I am learning MVC and stuck on creating foreign key. I have been creating the foreign key by using the same name of the primary key from its class. So I have following simple models,
public class User
{
[Key]
public Guid ID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
and another model of LoginHistory as,
public class LoginHistory
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public Guid UserID { get; set; }
public DateTime AttemptDateTime { get; set; }
}
Now this part I know that if I use UserID in the LoginHistory models then it will be created as foreign key. But what if I want to name the column as CustomUser in the model LoginHstory?
I have checked this question, Asp.net mvc entity framework code first associate foreign key with different name
According to its answer my model will be like this if I want to use different name as the primary key,
public class LoginHistory
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public Guid CustomUser { get; set; }
[ForeignKey("CustomUser")]
public virtual User User { get; set; }
}
As per the above solution I am using both the Association and Navigation Property. What if I just want to use the Association and not Navigation property? What is the rule of thumb for creating the Foreign key with different names? When the Navigation Property is required apart from selecting associated data?
There are many things done easier with fluent api but I like to do things with Data Annotations or initially I just want to understand the Data Annotations completely. Thanks
Upvotes: 0
Views: 3525
Reputation: 26
If you want to use data annotations, what you have done is perfectly fine, you should have the navigation property.
Upvotes: 1
Reputation: 397
If you don't need the navigation property there is no need to specify it as you are removing the navigation. Essentially you would be inserting LoginHistory directly from EF without the navigation property. No big deal, but keep in mind if you want to use Cascade Deletes or so, thsi will require a foreign key.
P.S. I have removed all data annotations and moved to FluentAPI. This gave me cleaner models that I pass around in my application.
Upvotes: 1