EntityFramework:无效的列名 *_ID1 [英] EntityFramework : Invalid column name *_ID1

查看:14
本文介绍了EntityFramework:无效的列名 *_ID1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为名为Employee"和Department"的几个表实现 DbContext员工与部门之间的关系是多对一的.即部门可以有很多员工.

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.

以下是我设计的 EntityFramework 类(CodeFirst 方法)

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'." 

我不确定为什么 EF 指的是 Department_ID1.是否需要在DbContextOnModelCreating方法中添加配置?

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

我使用的是EF版本6.1.1

推荐答案

经过一段时间后,我可以通过使用 public virtual Department Department { get; 上的 ForeignKey 属性来解决这个问题放;Employee 类的 } 属性.

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.

请看下面的代码.

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

这解决了我的问题.有没有其他解决方案来解决这个问题?使用流畅的 API?

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

这篇关于EntityFramework:无效的列名 *_ID1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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