我有以下文章模型。
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }
// Navigation properties
public virtual UserProfile Author { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
UserProfile
是 MVC4 标准项目中默认值的扩展版本。
现在,在我的脚手架控制器/视图中,无法进入Author
。
我的数据库 (MySQL) 包含一个名为 Author_UserId
的字段
int
。怎么了?
另外,是否真的有必要通过导航属性和AuthorId
来引用作者
在任何表上使用特定表的 2 个相同外键并不常见。这被解释为数据冗余。为了在没有任何冗余的情况下解决问题,我向您推荐以下模型:
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }//determine name of foreign key here of type primary key of navigatable table
// Navigation properties
[ForeignKey("AuthorId")]
public virtual UserProfile Author { get; set; }//column with name 'AuthorId'
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
上面的解决方案,用于自命名导航属性外键。我希望有用。