Home > OS >  Getting invalid column error when trying to query table in Entity Framework Core
Getting invalid column error when trying to query table in Entity Framework Core

Time:10-10

I have a table Employee in my database - these are the columns:

EmployeeId   Name  CreatedDate   UpdatedDate

This is my base class for domain entities:

public interface IBaseEntity
{
     public int Id { get; set; }
     
     public DateTime CreatedDate { get; set; }
     public DateTime UpdatedDate { get; set; }
}

public class BaseEntity : IBaseEntity
{
     public int Id { get; set; }
     
     public DateTime CreatedDate { get; set; }
     public DateTime UpdatedDate { get; set; }
}

Domain entities:

public class Employee : BaseEntity
{
    public string Name { get; set; }
    //other properties
}

public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
{
    public void Configure(EntityTypeBuilder<Employee> builder)
    {
        builder.ToTable("Employee");
        builder.HasKey(e=>e.Id);
        //other configurations
    }
}

public class MyDatabaseContext : DbContext
{
   private readonly IConfiguration _configuration;

   public MyDatabaseContext(IConfiguration configuration)
   {
        _configuration = configuration;
         Database.EnsureCreated(); 
   }

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

   public void Save()
   {
        this.SaveChanges();
   }
}

I already had existing database created so I created all this domain models and configuration based on existing database tables and relationships (No migrations).

Now when I am trying to get list of employees like this:

var myDatabaseContext = new MyDatabaseContext();
var emp = myDatabaseContext.Employee.ToList();

I get this error:

Invalid column name 'Id'

How do I make my base class property Id work with my individual tables as primary key with different names?

I'm using Entity Framework Core v6.0.9

CodePudding user response:

You are missing the definition for the column name. Right now EF Core is looking for a column called Id:

builder.Property(x => x.Id).HasColumnName("EmployeeId");

The docs for this are located here: https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=fluent-api,without-nrt#column-names

  • Related