简体   繁体   中英

EFCore generating Column that is not valid

When i try to access the employees table for the Northwind database i get an invalid column name error, this column does not exist in the database and i am not sure how it is created or how to prevent it. i tried not to map the generated name but it just increments it

Error:

System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'ManagerEmployeeID2'. at System.Data.SqlClient.SqlCommand.<>c.b__122_0(Task`1 result)

Employees model class:

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

In Northwind Employees table "ReportsTo" column is the FK (self-referencing constraint) to establish an employee-manager relationship. So your DbContext OnModelCreation method's Employee entity mapping will look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM