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

10,418

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.

Share:
10,418
Andres Felipe
Author by

Andres Felipe

Updated on June 19, 2022

Comments

  • Andres Felipe
    Andres Felipe almost 2 years

    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.