【发布时间】:2015-05-04 19:43:17
【问题描述】:
我正在学习 MVC 并坚持创建外键。我一直在通过使用其类中主键的相同名称来创建外键。所以我有以下简单的模型,
public class User
{
[Key]
public Guid ID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
还有另一个LoginHistory模型,
public class LoginHistory
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public Guid UserID { get; set; }
public DateTime AttemptDateTime { get; set; }
}
现在这部分我知道如果我在 LoginHistory 模型中使用 UserID,那么它将被创建为外键。但是,如果我想在模型 LoginHstory 中将列命名为 CustomUser 怎么办?
我已经检查了这个问题, Asp.net mvc entity framework code first associate foreign key with different name
根据它的回答,如果我想使用不同的名称作为主键,我的模型将是这样的,
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; }
}
根据上述解决方案,我同时使用关联和导航属性。如果我只想使用 Association 而不是 Navigation 属性怎么办?创建具有不同名称的外键的经验法则是什么?除了选择关联数据之外,何时需要导航属性?
使用 fluent api 可以更轻松地完成很多事情,但我喜欢使用数据注释来做事情,或者最初我只是想完全理解数据注释。谢谢
【问题讨论】:
标签: c# entity-framework