Description:
I defined the following Poco class to represent the customer table in the default (sakila) database:
using System;
using System.ComponentModel.DataAnnotations;
public class Customer
{
[Key]
[Column("customer_id")]
public Int16 CustomerId { get; set; }
[Column("store_id")]
public byte StoreId { get; set; }
[Column("first_name")]
public string FirstName { get; set; }
[Column("last_name")]
public string LastName { get; set; }
[Column("email")]
public string Email { get; set; }
[Column("active")]
public bool Active { get; set; }
[Column("create_date")]
public DateTime CreateDate { get; set; }
[Column("last_update")]
public DateTime LastUpdate { get; set; }
}
I then make an incredible basic CustomerContext class:
using Microsoft.EntityFrameworkCore;
public class CustomerContext : DbContext
{
public CustomerContext(DbContextOptions<CustomerContext> options)
: base(options)
{ }
public DbSet<Customer> Customer { get; set; }
}
Simple data retrieval using the context class pointing at my MySQL database will fail indicating that column CustomerId does not exist:
var db = CustomerContextFactory.Create(Configuration["ConnectionStrings:SampleConnection"]);
var customers = db.Customer.ToArray();
How to repeat:
1. Install sakila database with default schema and default data.
2. Put the shown code into a sample project that uses EntityFrameworkCore (I was working on a Mac)
3. Attempt to pull the customers out of the database
Suggested fix:
A work around is to add the following function to the CustomerContext class, which does work, but it would be nice if EF honored the Column attributes on the Poco class as well.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().Property(c => c.CustomerId).HasColumnName("customer_id");
modelBuilder.Entity<Customer>().Property(c => c.StoreId).HasColumnName("store_id");
modelBuilder.Entity<Customer>().Property(c => c.FirstName).HasColumnName("first_name");
modelBuilder.Entity<Customer>().Property(c => c.LastName).HasColumnName("last_name");
modelBuilder.Entity<Customer>().Property(c => c.Email).HasColumnName("email");
modelBuilder.Entity<Customer>().Property(c => c.Active).HasColumnName("active");
modelBuilder.Entity<Customer>().Property(c => c.CreateDate).HasColumnName("create_date");
modelBuilder.Entity<Customer>().Property(c => c.LastUpdate).HasColumnName("last_update");
}