I'm trying to code my object relationships with my database using EntityFramework (EFCore 5). My database has an unconventional many-to-many relationship. We have a Store table which has an integer ID primary key and related fields (name, et cetera), Customer, which has an ID primary key, a name, and other related fields.
Our StoreCustomer join table schema is the odd part. The join table has StoreID which points to a single Store, but instead of CustomerID, it is 'Customer Name'. It's not a one-to one relationship from StoreCustomer to Customer, because multiple Customers can have the same name. This is intended by the schema. Thus StoreCustomer to Store is a one-to-many relationship. My classes are laid out like so:
public partial class StoreCustomer
{
[Column("Store ID")]
public long StoreId { get; set; }
[Column("Customer Name")]
public string CustomerName { get; set; } = null!;
[Column]
public long Order { get; set; }
[ForeignKey(nameof(CustomerName))]
public ICollection<Customer> Customers { get; set; } = null!;
}
public partial class Customer
{
[Key]
[Column("Customer ID")]
public long CustomerId { get; set; }
[Column]
public string Name { get; set; } = null!;
}
And my OnModelCreating looks like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StoreCustomer>(entity =>
{
entity.HasKey(entity => new { entity.StoreId, entity.CustomerName, entity.Order });
entity.HasMany(sc => sc.Customers)
.WithOne()
.HasPrincipalKey(sc => sc.CustomerName);
});
modelBuilder.Entity<Customer>(entity =>
{
entity.Property(e => e.CustomerId).ValueGeneratedNever();
});
OnModelCreatingPartial(modelBuilder);
}
The issue is, when I call 'context.StoreCustomers.Include(sc => sc.Customers);', the resulting query has an extra column "Customer"."CustomerName" which of course causes an exception. It's like EFCore is creating a new ghost property for this column and I don't understand why. Why is it doing this? Also, in the future when weird stuff like this happens, are there ways to debug EF to catch it in the act so I understand why it's doing what it's doing?
EDIT: Sorry, I almost forgot to mention - I am using MS Access, so I am using the unofficial EntityFrameworkCore.Jet libraries to access it. I'm not sure if that has anything to do with it, but it is the reason I am using EFCore 5, because the library doesn't support 6 yet.