Entity Framework Foreign Key with different name

时间:2015-05-04 19:43:18

标签: c# entity-framework

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

2 个答案:

答案 0 :(得分:1)

如果您不需要导航属性,则无需在删除导航时指定它。 基本上你将直接从EF插入LoginHistory而没有导航属性。没什么大不了的,但是如果你想使用Cascade Deletes那么请记住,这将需要一个外键。

P.S。我已删除所有数据注释并移至FluentAPI。这给了我在我的应用程序中传递的更清晰的模型。

答案 1 :(得分:1)

如果你想使用数据注释,你所做的就是完全没问题,你应该有导航属性。