I get a invalid column name exception while accessing a Entity field












1















I have recently added a column named 'CreatedBy'in the Course table which reference the UserID in the user table in the database and created a corresponding entity field for it. But while accessing the CreatedBy field I get a error:
System.Data.SqlClient.SqlException: Invalid column name 'CreatedByID'.



I tried different means of data annotations but it did not work.



Entities:



public partial class Course
{
public Course()
{
this.CourseLessons = new List<CourseLesson>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }
public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}

public partial class WebsiteUser
{
public WebsiteUser()
{
// Other code
}
[Key]
public int UserID { get; set; }

[Required]
public string Name { get; set; }

[Required]
public string Email { get; set; }
}

public ActionResult EditCourse()
{
SQLContext context = new SQLContext();
var deletethis = context.Courses.First().CreatedBy; // Gives error
return View(context.Courses);
}









share|improve this question























  • what Is your entity type? Database First or Code first? did you update your database and migration?

    – AmirReza-Farahlagha
    Dec 31 '18 at 13:03
















1















I have recently added a column named 'CreatedBy'in the Course table which reference the UserID in the user table in the database and created a corresponding entity field for it. But while accessing the CreatedBy field I get a error:
System.Data.SqlClient.SqlException: Invalid column name 'CreatedByID'.



I tried different means of data annotations but it did not work.



Entities:



public partial class Course
{
public Course()
{
this.CourseLessons = new List<CourseLesson>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }
public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}

public partial class WebsiteUser
{
public WebsiteUser()
{
// Other code
}
[Key]
public int UserID { get; set; }

[Required]
public string Name { get; set; }

[Required]
public string Email { get; set; }
}

public ActionResult EditCourse()
{
SQLContext context = new SQLContext();
var deletethis = context.Courses.First().CreatedBy; // Gives error
return View(context.Courses);
}









share|improve this question























  • what Is your entity type? Database First or Code first? did you update your database and migration?

    – AmirReza-Farahlagha
    Dec 31 '18 at 13:03














1












1








1








I have recently added a column named 'CreatedBy'in the Course table which reference the UserID in the user table in the database and created a corresponding entity field for it. But while accessing the CreatedBy field I get a error:
System.Data.SqlClient.SqlException: Invalid column name 'CreatedByID'.



I tried different means of data annotations but it did not work.



Entities:



public partial class Course
{
public Course()
{
this.CourseLessons = new List<CourseLesson>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }
public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}

public partial class WebsiteUser
{
public WebsiteUser()
{
// Other code
}
[Key]
public int UserID { get; set; }

[Required]
public string Name { get; set; }

[Required]
public string Email { get; set; }
}

public ActionResult EditCourse()
{
SQLContext context = new SQLContext();
var deletethis = context.Courses.First().CreatedBy; // Gives error
return View(context.Courses);
}









share|improve this question














I have recently added a column named 'CreatedBy'in the Course table which reference the UserID in the user table in the database and created a corresponding entity field for it. But while accessing the CreatedBy field I get a error:
System.Data.SqlClient.SqlException: Invalid column name 'CreatedByID'.



I tried different means of data annotations but it did not work.



Entities:



public partial class Course
{
public Course()
{
this.CourseLessons = new List<CourseLesson>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }
public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}

public partial class WebsiteUser
{
public WebsiteUser()
{
// Other code
}
[Key]
public int UserID { get; set; }

[Required]
public string Name { get; set; }

[Required]
public string Email { get; set; }
}

public ActionResult EditCourse()
{
SQLContext context = new SQLContext();
var deletethis = context.Courses.First().CreatedBy; // Gives error
return View(context.Courses);
}






c# entity-framework model-view-controller foreign-keys






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 31 '18 at 12:40









SujoySujoy

9411




9411













  • what Is your entity type? Database First or Code first? did you update your database and migration?

    – AmirReza-Farahlagha
    Dec 31 '18 at 13:03



















  • what Is your entity type? Database First or Code first? did you update your database and migration?

    – AmirReza-Farahlagha
    Dec 31 '18 at 13:03

















what Is your entity type? Database First or Code first? did you update your database and migration?

– AmirReza-Farahlagha
Dec 31 '18 at 13:03





what Is your entity type? Database First or Code first? did you update your database and migration?

– AmirReza-Farahlagha
Dec 31 '18 at 13:03












2 Answers
2






active

oldest

votes


















3














"CreatedByID" is the default conventional name for the database table column corresponding to the CreatedByID property which you mapped as a foreign key here



public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }


In order to change the conventional column name you could use the [Column] data annotation (attribute):



[Column("CreatedBy")]
public int? CreatedByID { get; set; }


or fluent API:



modelBuilder.Entity<Course>()
.Property(e => e.CreatedById)
.HasColumnName("CreatedBy");


To recap, ForeignKey attribute specifies the name of the entity property to be mapped as FK column, while Column attribute specifies the name of the table column mapped to that property.






share|improve this answer































    -3














    Try to use single quote




    '




    instead double quote




    "




    it worked for me in Postgresql database.



    For example



    [ForeignKey('CreatedByID')]





    share|improve this answer
























    • Why try that? Did you try it?

      – CodingYoshi
      Dec 31 '18 at 12:55











    • Oh mein god sure i tried, just wanted to be nice.

      – Kamil
      Dec 31 '18 at 12:56











    • If you tried it, you would not ask someone else to try it.

      – CodingYoshi
      Dec 31 '18 at 12:58











    • This isn't even valid C# code!

      – Gert Arnold
      Dec 31 '18 at 13:02











    • Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

      – Tanveer Badar
      Dec 31 '18 at 13:24











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987652%2fi-get-a-invalid-column-name-exception-while-accessing-a-entity-field%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    "CreatedByID" is the default conventional name for the database table column corresponding to the CreatedByID property which you mapped as a foreign key here



    public int? CreatedByID { get; set; }

    [ForeignKey("CreatedByID")]
    public virtual WebsiteUser CreatedBy { get; set; }


    In order to change the conventional column name you could use the [Column] data annotation (attribute):



    [Column("CreatedBy")]
    public int? CreatedByID { get; set; }


    or fluent API:



    modelBuilder.Entity<Course>()
    .Property(e => e.CreatedById)
    .HasColumnName("CreatedBy");


    To recap, ForeignKey attribute specifies the name of the entity property to be mapped as FK column, while Column attribute specifies the name of the table column mapped to that property.






    share|improve this answer




























      3














      "CreatedByID" is the default conventional name for the database table column corresponding to the CreatedByID property which you mapped as a foreign key here



      public int? CreatedByID { get; set; }

      [ForeignKey("CreatedByID")]
      public virtual WebsiteUser CreatedBy { get; set; }


      In order to change the conventional column name you could use the [Column] data annotation (attribute):



      [Column("CreatedBy")]
      public int? CreatedByID { get; set; }


      or fluent API:



      modelBuilder.Entity<Course>()
      .Property(e => e.CreatedById)
      .HasColumnName("CreatedBy");


      To recap, ForeignKey attribute specifies the name of the entity property to be mapped as FK column, while Column attribute specifies the name of the table column mapped to that property.






      share|improve this answer


























        3












        3








        3







        "CreatedByID" is the default conventional name for the database table column corresponding to the CreatedByID property which you mapped as a foreign key here



        public int? CreatedByID { get; set; }

        [ForeignKey("CreatedByID")]
        public virtual WebsiteUser CreatedBy { get; set; }


        In order to change the conventional column name you could use the [Column] data annotation (attribute):



        [Column("CreatedBy")]
        public int? CreatedByID { get; set; }


        or fluent API:



        modelBuilder.Entity<Course>()
        .Property(e => e.CreatedById)
        .HasColumnName("CreatedBy");


        To recap, ForeignKey attribute specifies the name of the entity property to be mapped as FK column, while Column attribute specifies the name of the table column mapped to that property.






        share|improve this answer













        "CreatedByID" is the default conventional name for the database table column corresponding to the CreatedByID property which you mapped as a foreign key here



        public int? CreatedByID { get; set; }

        [ForeignKey("CreatedByID")]
        public virtual WebsiteUser CreatedBy { get; set; }


        In order to change the conventional column name you could use the [Column] data annotation (attribute):



        [Column("CreatedBy")]
        public int? CreatedByID { get; set; }


        or fluent API:



        modelBuilder.Entity<Course>()
        .Property(e => e.CreatedById)
        .HasColumnName("CreatedBy");


        To recap, ForeignKey attribute specifies the name of the entity property to be mapped as FK column, while Column attribute specifies the name of the table column mapped to that property.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 14:06









        Ivan StoevIvan Stoev

        103k774126




        103k774126

























            -3














            Try to use single quote




            '




            instead double quote




            "




            it worked for me in Postgresql database.



            For example



            [ForeignKey('CreatedByID')]





            share|improve this answer
























            • Why try that? Did you try it?

              – CodingYoshi
              Dec 31 '18 at 12:55











            • Oh mein god sure i tried, just wanted to be nice.

              – Kamil
              Dec 31 '18 at 12:56











            • If you tried it, you would not ask someone else to try it.

              – CodingYoshi
              Dec 31 '18 at 12:58











            • This isn't even valid C# code!

              – Gert Arnold
              Dec 31 '18 at 13:02











            • Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

              – Tanveer Badar
              Dec 31 '18 at 13:24
















            -3














            Try to use single quote




            '




            instead double quote




            "




            it worked for me in Postgresql database.



            For example



            [ForeignKey('CreatedByID')]





            share|improve this answer
























            • Why try that? Did you try it?

              – CodingYoshi
              Dec 31 '18 at 12:55











            • Oh mein god sure i tried, just wanted to be nice.

              – Kamil
              Dec 31 '18 at 12:56











            • If you tried it, you would not ask someone else to try it.

              – CodingYoshi
              Dec 31 '18 at 12:58











            • This isn't even valid C# code!

              – Gert Arnold
              Dec 31 '18 at 13:02











            • Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

              – Tanveer Badar
              Dec 31 '18 at 13:24














            -3












            -3








            -3







            Try to use single quote




            '




            instead double quote




            "




            it worked for me in Postgresql database.



            For example



            [ForeignKey('CreatedByID')]





            share|improve this answer













            Try to use single quote




            '




            instead double quote




            "




            it worked for me in Postgresql database.



            For example



            [ForeignKey('CreatedByID')]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 31 '18 at 12:48









            KamilKamil

            679




            679













            • Why try that? Did you try it?

              – CodingYoshi
              Dec 31 '18 at 12:55











            • Oh mein god sure i tried, just wanted to be nice.

              – Kamil
              Dec 31 '18 at 12:56











            • If you tried it, you would not ask someone else to try it.

              – CodingYoshi
              Dec 31 '18 at 12:58











            • This isn't even valid C# code!

              – Gert Arnold
              Dec 31 '18 at 13:02











            • Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

              – Tanveer Badar
              Dec 31 '18 at 13:24



















            • Why try that? Did you try it?

              – CodingYoshi
              Dec 31 '18 at 12:55











            • Oh mein god sure i tried, just wanted to be nice.

              – Kamil
              Dec 31 '18 at 12:56











            • If you tried it, you would not ask someone else to try it.

              – CodingYoshi
              Dec 31 '18 at 12:58











            • This isn't even valid C# code!

              – Gert Arnold
              Dec 31 '18 at 13:02











            • Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

              – Tanveer Badar
              Dec 31 '18 at 13:24

















            Why try that? Did you try it?

            – CodingYoshi
            Dec 31 '18 at 12:55





            Why try that? Did you try it?

            – CodingYoshi
            Dec 31 '18 at 12:55













            Oh mein god sure i tried, just wanted to be nice.

            – Kamil
            Dec 31 '18 at 12:56





            Oh mein god sure i tried, just wanted to be nice.

            – Kamil
            Dec 31 '18 at 12:56













            If you tried it, you would not ask someone else to try it.

            – CodingYoshi
            Dec 31 '18 at 12:58





            If you tried it, you would not ask someone else to try it.

            – CodingYoshi
            Dec 31 '18 at 12:58













            This isn't even valid C# code!

            – Gert Arnold
            Dec 31 '18 at 13:02





            This isn't even valid C# code!

            – Gert Arnold
            Dec 31 '18 at 13:02













            Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

            – Tanveer Badar
            Dec 31 '18 at 13:24





            Did this even compile for you? I guess if it didn't compile, then you did not get to the runtime exception part either, hence problem solved in a sense?

            – Tanveer Badar
            Dec 31 '18 at 13:24


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987652%2fi-get-a-invalid-column-name-exception-while-accessing-a-entity-field%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas