[英]Setting up foreign key in ASP.NET MVC 4
I have 2 models and want to create a foreign key relationship. 我有2个模型,想要创建一个外键关系。 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; }
}
When I attempt to add new user note I get: The ForeignKeyAttribute on property 'UserId' on type 'note.DO.Models.UserNotes' is not valid. 当我尝试添加新用户注释时,我得到: 类型为“note.DO.Models.UserNotes”的属性“UserId”上的ForeignKeyAttribute无效。 The navigation property 'UserProfile' was not found on the dependent type 'note.DO.Models.UserNotes'.
在依赖类型“note.DO.Models.UserNotes”上找不到导航属性“UserProfile”。 The Name value should be a valid navigation property name.
Name值应该是有效的导航属性名称。
I have tried a lot of combinations including those found in similar questions but none of them worked. 我尝试了很多组合,包括在类似问题中找到的组合,但没有一组合作。
Try this : 试试这个 :
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.
您的错误消息显示缺少“UserProfile”属性,您只需添加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.