Why is EF Core adding shadow fields on many to many join table queries?
I am migrating a MySQL database first EF 6 project to EF Core using EF Core scaffolding templates and EF Core Power Tools. Every thing is working except a many to many join table that joins the same parent table with a payload. This table structure worked fine in EF 6.
When I run the code I have an extra 3 shadow partial primary key fields with 1-3 added to the end. I have seen similar issues raised multiple times but from what I can tell the scaffolded model builder code looks legit with correct foreign keys. btw there are other join tables in the schema that are joining two separate tables with a payload and they have no issues.
Include your code
Parent Table
CREATE TABLE ProductGroup (
ProductGroupId bigint NOT NULL AUTO_INCREMENT,
Checksum char(36) NOT NULL,
Created datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
Updated datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
Name varchar(45) NOT NULL,
Description varchar(255) DEFAULT NULL,
Saleable bit(1) NOT NULL DEFAULT b'1',
StockItem bit(1) NOT NULL DEFAULT b'0',
MainProduct bit(1) NOT NULL DEFAULT b'0',
Available bit(1) NOT NULL DEFAULT b'1',
Sundry bit(1) NOT NULL DEFAULT b'0',
MinOrderQty int NOT NULL DEFAULT '1',
MaxOrderQty int NOT NULL DEFAULT '40',
LinkToPromotion bit(1) NOT NULL DEFAULT b'0',
ProductGroupFamilyId int NOT NULL DEFAULT '0',
PRIMARY KEY (ProductGroupId),
KEY ProductGroupFamilyId_idx (ProductGroupFamilyId),
CONSTRAINT ProductGroupFamilyId FOREIGN KEY (ProductGroupFamilyId) REFERENCES ProductGroupFamily (ProductGroupFamilyId)
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Join table
CREATE TABLE ProductGroupRelationship (
ProductGroupId bigint NOT NULL,
RelatedProductGroupId bigint NOT NULL,
ProductGroupRelationshipTypeId int NOT NULL,
Qty int DEFAULT NULL,
Optional bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (ProductGroupId,RelatedProductGroupId),
KEY productgrouprelationship_relatedproductgroupid_idx (RelatedProductGroupId),
KEY productgrouprelationship_productgroupid_idx (ProductGroupId),
KEY productgrouprelationship_productgrouprelationshiptypeid_idx (ProductGroupRelationshipTypeId),
CONSTRAINT productgrouprelationship_productgroupid FOREIGN KEY (ProductGroupId) REFERENCES ProductGroup (ProductGroupId),
CONSTRAINT productgrouprelationship_productgrouprelationshiptypeid FOREIGN KEY (ProductGroupRelationshipTypeId) REFERENCES ProductGroupRelationshipType (ProductGroupRelationshipTypeId),
CONSTRAINT productgrouprelationship_relatedproductgroupid FOREIGN KEY (RelatedProductGroupId) REFERENCES ProductGroup (ProductGroupId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
Model builder code created via scaffolding
modelBuilder.Entity<ProductGroupRelationship>(entity =>
{
entity.HasKey(e => new { e.ProductGroupId, e.RelatedProductGroupId })
.HasName("PRIMARY")
.HasAnnotation("MySql:IndexPrefixLength", new[] { 0, 0 });
entity
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.HasIndex(e => e.ProductGroupId, "productgrouprelationship_productgroupid_idx");
entity.HasIndex(e => e.ProductGroupRelationshipTypeId, "productgrouprelationship_productgrouprelationshiptypeid_idx");
entity.HasIndex(e => e.RelatedProductGroupId, "productgrouprelationship_relatedproductgroupid_idx");
entity.HasOne(d => d.ProductGroup).WithMany(p => p.ProductGroupRelationship)
.HasForeignKey(d => d.ProductGroupId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("productgrouprelationship_productgroupid");
entity.HasOne(d => d.ProductGroupRelationshipType).WithMany(p => p.ProductGroupRelationship)
.HasForeignKey(d => d.ProductGroupRelationshipTypeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("productgrouprelationship_productgrouprelationshiptypeid");
entity.HasOne(d => d.RelatedProductGroup).WithMany(p => p.RelatedProductGroupRelationship)
.HasForeignKey(d => d.RelatedProductGroupId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("productgrouprelationship_relatedproductgroupid");
});
Entity
public partial class ProductGroupRelationship
{
public long ProductGroupId { get; set; }
public long RelatedProductGroupId { get; set; }
public int ProductGroupRelationshipTypeId { get; set; }
public int? Qty { get; set; }
public bool Optional { get; set; }
public virtual ProductGroup ProductGroup { get; set; }
public virtual ProductGroupRelationshipType ProductGroupRelationshipType { get; set; }
public virtual ProductGroup RelatedProductGroup { get; set; }
}
Attempt to get records from ProductGroupRelationship table
var productGroupRelationship = db.ProductGroupRelationship.Where(m => m.ProductGroupId.Equals(2)).ToList();
Debug output
Microsoft.EntityFrameworkCore.Infrastructure: Debug: Entity Framework Core 8.0.7 initialized 'RetailDbContext' using provider 'MySql.EntityFrameworkCore:(null)' with options: SensitiveDataLoggingEnabled DetailedErrorsEnabled
Microsoft.EntityFrameworkCore.Query: Debug: Compiling query expression:
'DbSet<ProductGroupRelationship>()
.Where(m => m.ProductGroupId.Equals(2))'
Microsoft.EntityFrameworkCore.Query: Debug: Generated query execution expression:
'queryContext => new SingleQueryingEnumerable<ProductGroupRelationship>(
(RelationalQueryContext)queryContext,
RelationalCommandCache.QueryExpression(
Projection Mapping:
EmptyProjectionMember -> Dictionary<IProperty, int> { [Property: ProductGroupRelationship.ProductGroupId (long) Required PK FK Index AfterSave:Throw, 0], [Property: ProductGroupRelationship.RelatedProductGroupId (long) Required PK FK Index AfterSave:Throw, 1], [Property: ProductGroupRelationship.Optional (bool) Required, 2], [Property: ProductGroupRelationship.ProductGroupId1 (no field, long?) Shadow FK Index, 3], [Property: ProductGroupRelationship.ProductGroupId2 (no field, long?) Shadow FK Index, 4], [Property: ProductGroupRelationship.ProductGroupId3 (no field, long?) Shadow FK Index, 5], [Property: ProductGroupRelationship.ProductGroupRelationshipTypeId (int) Required FK Index, 6], [Property: ProductGroupRelationship.Qty (int?), 7] }
SELECT p.ProductGroupId, p.RelatedProductGroupId, p.Optional, p.ProductGroupId1, p.ProductGroupId2, p.ProductGroupId3, p.ProductGroupRelationshipTypeId, p.Qty
FROM ProductGroupRelationship AS p
WHERE p.ProductGroupId == 2),
null,
Func<QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator, ProductGroupRelationship>,
DayOneCo.Models.Retail.RetailDbContext,
False,
True,
True
)'
Microsoft.EntityFrameworkCore.Database.Command: Debug: Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT `p`.`ProductGroupId`, `p`.`RelatedProductGroupId`, `p`.`Optional`, `p`.`ProductGroupId1`, `p`.`ProductGroupId2`, `p`.`ProductGroupId3`, `p`.`ProductGroupRelationshipTypeId`, `p`.`Qty`
FROM `ProductGroupRelationship` AS `p`
WHERE `p`.`ProductGroupId` = 2
Note the extra fields: ProductGroupId1, ProductGroupId2 & ProductGroupId3
Any ideas on this? From what I have read most times this issue has been resolved by explicitly adding foreign keys for join tables. As you can see the scaffolding has already done this as far as I can tell. I've tried adding/tweaking/removing HasPrincipalKey, HasForeignKey but nothing is making a difference. Could it possibly be the naming conventions in EF Core not liking RelatedProductGroupId and looking for ProductGroupId1? I'm stumped at this point so any help would be greatly appreciated.
Thanks!
Include provider and version information
EF Core version: 8.0.7 Database provider: MySql.EntityFrameworkCore 8.0.5 or Pomelo.EntityFrameworkCore.MySql 8.01 (Same issue with both) Target framework: 8 Operating system: Win 10 IDE: Visual Studio 2022 17.11.0 Preview 7.0
Just tested with EF Core 8.0.8 and it is still an issue.
Most likely you need to configure the foreign key properties explicitly, see https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many#basic-many-to-many
If you are still experiencing this issue please also share the code for ProductGroup and the related model builder calls.
Thanks for the reply.
Scaffolding is already configuring the foreign keys explicitly on ProductGroupRelationship. Its not obvious to me from the documentation how I could do it differently.
Model builder for ProductGroup
modelBuilder.Entity<ProductGroup>(entity =>
{
entity.HasKey(e => e.ProductGroupId).HasName("PRIMARY");
entity.HasIndex(e => e.ProductGroupFamilyId, "ProductGroupFamilyId_idx");
entity.Property(e => e.Created)
.HasDefaultValueSql("CURRENT_TIMESTAMP")
.HasColumnType("datetime");
entity.Property(e => e.Description).HasMaxLength(255);
entity.Property(e => e.MaxOrderQty).HasDefaultValueSql("'40'");
entity.Property(e => e.MinOrderQty).HasDefaultValueSql("'1'");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(45);
entity.Property(e => e.Updated)
.ValueGeneratedOnAddOrUpdate()
.HasDefaultValueSql("CURRENT_TIMESTAMP")
.HasColumnType("datetime");
entity.HasOne(d => d.ProductGroupFamily).WithMany(p => p.ProductGroup)
.HasForeignKey(d => d.ProductGroupFamilyId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("ProductGroupFamilyId");
});
ProductGroup entity
public partial class ProductGroup
{
public long ProductGroupId { get; set; }
public Guid Checksum { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Saleable { get; set; }
public bool StockItem { get; set; }
public bool MainProduct { get; set; }
public bool Available { get; set; }
public bool Sundry { get; set; }
public int MinOrderQty { get; set; }
public int MaxOrderQty { get; set; }
public bool LinkToPromotion { get; set; }
public int ProductGroupFamilyId { get; set; }
public virtual ICollection<PostcodeDeliveryFee> PostcodeDeliveryFee { get; set; } = new List<PostcodeDeliveryFee>();
public virtual ICollection<Product> Product { get; set; } = new List<Product>();
public virtual ProductGroupFamily ProductGroupFamily { get; set; }
public virtual ICollection<ProductGroupRelationship> ProductGroupRelationship { get; set; } = new List<ProductGroupRelationship>();
public virtual ICollection<ProductGroupRelationship> RelatedProductGroupRelationship { get; set; } = new List<ProductGroupRelationship>();
public virtual ICollection<ProductGroupTagType> ProductGroupTagType { get; set; } = new List<ProductGroupTagType>();
}
Hmm. I tried creating a context with just those 2 types and I don't see the issue. This is the query generated by Pomelo.EntityFrameworkCore.MySql 8.0.1
SELECT `p`.`ProductGroupId`, `p`.`RelatedProductGroupId`, `p`.`Optional`, `p`.`ProductGroupRelationshipTypeId`, `p`.`Qty`
FROM `ProductGroupRelationship` AS `p`
WHERE `p`.`ProductGroupId` = 2
Can you create a small repro project?
Interesting, I will try taking your tack and start adding entities in the context until it breaks. There are others that reference or are referenced by ProductGroup. By the end of it I will have hopefully solved the issue or have a repo I can demonstrate with.
Got it fixed.
Short answer: I had expression-body properties in a partial class that required [NotMapped] attribute
Long answer:
I created a new project and rebuilt the context and entities to by identical to my original project. I had no issue querying ProductGroupRelationship. So that excluded the scaffolding as an issue and triggered me to think a partial was the issue. I had already been through all the partials, created in the ef 6 project, and added [NotMapped] for any properties I could find with getter setters but not those defined with an expression-body. After adding [NotMapped] to those properties the application now runs as expected.
Thanks for your help Andriy, much appreciated