EFCore生成的列无效

时间:2019-03-21 21:06:16

标签: c# .net-core entity-framework-core

当我尝试访问Northwind数据库的employees表时,收到无效的列名错误,该列在数据库中不存在,并且我不确定如何创建或防止它。我试图不映射生成的名称,但只会增加它

错误:

  

System.Data.SqlClient.SqlException(0x80131904):无效的列名   “ ManagerEmployeeID2”。在   System.Data.SqlClient.SqlCommand。<> c.b__122_0(Task`1   结果)

员工模型类:

namespace UWofS.CS7
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public DateTime? BirthDate { get; set; }
        public DateTime? HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }
        public string Extension { get; set; }
        public string Notes { get; set; }
        public int ReportsTo { get; set; }
        public Employee Manager { get; set; }
        //public ICollection<Order> Orders { get; set; }
        [NotMapped]
        public Object ManagerEmployeeID { get; set; }
        [NotMapped]
        public Object ManagerEmployeeID1 { get; set; }
    }
}

Index.cshtml.cs

    namespace WebApp1.Pages.Employees
{
    public class IndexModel : PageModel
    {
        private readonly UWofS.CS7.Northwind _context;

        public IndexModel(UWofS.CS7.Northwind context)
        {
            _context = context;
        }

        public IList<Employee> Employee { get;set; }

        public async Task OnGetAsync()
        {
            try
            {
                Employee = await _context.Employees.ToListAsync();
            }
            catch(Exception ex)
            {
                Console.Write(ex);
                if (System.Diagnostics.Debugger.IsAttached == false)
                {
                    System.Diagnostics.Debugger.Launch();
                }
                //System.Environment.Exit(13);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在Northwind员工表中,“ ReportsTo”列是用于建立员工-经理关系的FK(自引用约束)。因此,您的DbContext OnModelCreation方法的Employee实体映射将如下所示:

modelBuilder.Entity<Employee>() .HasOne(x => x.Manager) .WithMany() .HasForeignKey(x => x.ReportsTo);

相关问题