0

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

1 Answer 1

2

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%2Cwithout-nrt#column-names

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.