实体框架.net:“名称值应该是有效的导航属性名称。” [英] Entity Framework .net: "The Name value should be a valid navigation property name."

查看:78
本文介绍了实体框架.net:“名称值应该是有效的导航属性名称。”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用ASP.Net启动一个项目,并且正在关注Microsoft的训练营。我试图对已发布的api进行REST请求,但遇到下一个异常:

Hello I'm starting a project with ASP.Net and I'm following the Training Camps of Microsoft. I was trying to make a REST petition to my published api, and I got the next exception:


属性 QuestionId上的ForeignKeyAttribute
类型 PlataformaTest.Models.AnswerModel无效。在依赖类型
PlataformaTest.Models.AnswerModel上找不到导航
属性 OptionModel。 Name值应该是有效的
导航属性
name。, exceptionType: System.InvalidOperationException

The ForeignKeyAttribute on property 'QuestionId' on type 'PlataformaTest.Models.AnswerModel' is not valid. The navigation property 'OptionModel' was not found on the dependent type 'PlataformaTest.Models.AnswerModel'. The Name value should be a valid navigation property name.","exceptionType":"System.InvalidOperationException"

顺便说一句,我并没有逐字逐句地训练,我改了一些名字,所以,只是想找出从零开始的所有过程。

By the way, I'm not following the Training excercise verbatim, I've changed some names and so, just to try to find out how would be all the process from zero.

非常感谢您的帮助和指导。

Any help and guidance is really appreciated. Thank you.

推荐答案

好,我已经解决了这个问题万一有人遇到相同的问题,这里就是问题和答案:

Ok. I've solved this issue. Just in case anyone have the same problem, here is the problem and the answer:

我有我的实体,例如:

namespace PlataformaTest.Models
{
    public class AnswerModel
    {
        public int Id { get; set; }

        public string UserId { get; set; }

        [ForeignKey("OptionModel"), Column(Order = 0)]
        public int QuestionId { get; set; }

        [ForeignKey("OptionModel"), Column(Order = 1)]
        public int OptionId { get; set; }

        [JsonIgnore]
        public virtual OptionModel OptionModelEx { get; set; }
    }
}

但是我发现了,

ForeignKey("OptionModel") 

必须具有与虚拟变量相同的名称。像这样:

has to have the same name of the "Virtual" variable. Like this:

namespace PlataformaTest.Models
{
    public class AnswerModel
    {
        public int Id { get; set; }

        public string UserId { get; set; }

        [ForeignKey("OptionModel"), Column(Order = 0)]
        public int QuestionId { get; set; }

        [ForeignKey("OptionModel"), Column(Order = 1)]
        public int OptionId { get; set; }

        [JsonIgnore]
        public virtual OptionModel OptionModel { get; set; }
    }
}

我以为它必须有类,但不是。它会寻找对象的名称以映射实体的外键。

I thought it had to have the name of the Class, but it doesn't. It looks for the name of the object to map the Entity's Foreign Key.

这篇关于实体框架.net:“名称值应该是有效的导航属性名称。”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆