C# 在 ASP.NET MVC 4 中设置外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19517451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:10:18  来源:igfitidea点击:

Setting up foreign key in ASP.NET MVC 4

c#asp.netasp.net-mvcasp.net-mvc-4

提问by Pawe? Duda

I have 2 models and want to create a foreign key relationship. Basically each note should be assigned to a user.

我有 2 个模型,想创建一个外键关系。基本上每个音符都应该分配给一个用户。

[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. 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.

当我尝试添加新的用户注释时,我得到: “note.DO.Models.UserNotes”类型上的“UserId”属性上的 ForeignKeyAttribute 无效。在依赖类型“note.DO.Models.UserNotes”上找不到导航属性“UserProfile”。Name 值应该是有效的导航属性名称。

I have tried a lot of combinations including those found in similar questions but none of them worked.

我尝试了很多组合,包括在类似问题中找到的组合,但都没有奏效。

采纳答案by Réda Mattar

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”属性,您只需添加它。