Search code examples
c#-4.0entity-framework-6

EntityFramework : Invalid column name *_ID1


I am trying to implement DbContext for couple of tables called 'Employee' and 'Department' Relationship between Employee and Department is many to one. i.e. department can have many employees.

Below are the EntityFramework classes I designed ( CodeFirst approach )

    [Table("Employee")]
    public class Employee
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Column("Name")]
        public string Name { get; set; }

        [Column("Department_ID")]        
        public int Department_ID { get; set; }

        public virtual Department Department { get; set; }
    }

[Table("Department")]
    public class Department
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [Column("Name")]        
        public string Name { get; set; }

        public virtual ICollection<Employee>  Employees { get; set; }
    }

While adding Employee record I am getting below exception

"Invalid column name 'Department_ID1'." 

I am not sure why EF is referring to Department_ID1. Do I need to add configuration in OnModelCreating method of DbContext?

I am using EF version 6.1.1


Solution

  • Hi After spending some time I could fix this problem by using ForeignKey attribute on public virtual Department Department { get; set; } property of Employee class.

    Please see below code.

     [Table("Employee")]
    public class Employee
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        [Column("Name")]
        public string Name { get; set; }
    
        [Column("Department_ID")]        
        public int Department_ID { get; set; }
    
        [ForeignKey("Department_ID")]
        public virtual Department Department { get; set; }
    }
    

    This fixed my problem. Are there any other solution to fix this? Using fluent API?