在ASP.NET中建立外键MVC 4 [英] Setting up foreign key in ASP.NET MVC 4
问题描述
我有2个型号,并希望创建一个外键关系。基本上每个音符应分配给用户。
I have 2 models and want to create a foreign key relationship. Basically each note should be assigned to a user.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
[Table("UserNotes")]
public class UserNotes
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int NoteId { get; set; }
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Added { get; set; }
public DateTime? Edited { get; set; }
}
当我尝试添加新用户注意事项我得到:
的ForeignKeyAttribute财产用户ID上输入note.DO.Models.UserNotes'无效。该导航属性用户配置并没有对因类型中找到note.DO.Models.UserNotes。 Name值应该是一个有效的导航属性的名称。的
When I attempt to add new user note I get: The ForeignKeyAttribute on property 'UserId' on type 'note.DO.Models.UserNotes' is not valid. The navigation property 'UserProfile' was not found on the dependent type 'note.DO.Models.UserNotes'. The Name value should be a valid navigation property name.
我已经尝试了很多组合,包括那些在类似的问题找到,但没有一次成功的。
I have tried a lot of combinations including those found in similar questions but none of them worked.
推荐答案
试试这个:
public virtual int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }
这样,你配对的外键财产导航属性。
This way, you pair foreign key property with navigation property.
编辑:你也可以写这样的:
Edit : you can also write it like this :
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
这两个片段给出相同的结果。您的错误信息说:用户配置的属性丢失,你只需要添加它。
Those two snippets gives the same result. Your error message says that "UserProfile" property is missing, you just have to add it.
这篇关于在ASP.NET中建立外键MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!