Entity Framework .net: “The Name value should be a valid navigation property name.”

ぐ巨炮叔叔 提交于 2019-12-10 13:13:26

问题


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:

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.


回答1:


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

I had my entities like:

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; }
    }
}

But I found out, that

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.



来源:https://stackoverflow.com/questions/32314967/entity-framework-net-the-name-value-should-be-a-valid-navigation-property-nam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!