4

I must be creating the composite key incorrectly or connecting it to the related entity incorrectly. I can get it to work in a simplified scenario of a single key, but the composite key fails. I'll show both working and non working versions.

My classes:

public class Parts {
   public string PartID { get; set; }
   public string Revision { get; set; } 
}

public class InstanceHistories {
    public int HistoryID { get; set; }
    public string PartID { get; set; }
    public string Revision { get; set; }
    public virtual Parts Part { get; set; }
}

Fluent API - That works

 modelBuilder.Entity<Parts>().HasKey(p => new { p.PartID });

 modelBuilder.Entity<InstanceHistories>().HasKey(i => i.HistoryID);
 modelBuilder.Entity<InstanceHistories>().HasRequired(i => i.Part);

Repo call

history = await repo.All
                    .Include(b => b.Part)
                    .Where(i => i.PartID== partIDToSearch).ToListAsync();

This repo call will load back my related Part object without any issues.

When I change the Fluent API to make the part have a composite key, my repo call will no longer return the related entity.

Non working Fluent API update

modelBuilder.Entity<Parts>().HasKey(p => new { p.PartID, p.Revision });

I have tried a few different scenarios of .WithMany(), .HasForeignKey(), .HasOptional() but nothing really seems to kick the Part back. I even tried to Lazy Load and they wont return so I know something must be up with my setup. Has anyone come across this scenario?

Edit

Even when I force the SQL to be shown (ie uow.Context.Database.Log = Console.WriteLine;), I see the related entity appear in the joined result.

Also, I do not receive any errors. Just null return on the Part object.

markokstate
  • 923
  • 2
  • 14
  • 28
  • 1
    The posted sample model and configuration are fine. Tested in a clean environment (latest EF6.1.3, SqlServer db), everything works as expected (the `Part` property is populated). Something has to be different in your real scenario. Without providing reproducible sample, I don't see how we can help. – Ivan Stoev Jan 18 '17 at 21:19
  • Oh interesting... I'll rebuild on a clean setup to see if I get the same result. Thanks @IvanStoev – markokstate Jan 18 '17 at 23:12
  • Are you running a migration after you change the key? – DavidG Jan 24 '17 at 01:11
  • Not running any EF migrations. – markokstate Jan 24 '17 at 22:31
  • Have you setup the composite key on the parts table in the database? – AperioOculus Jan 25 '17 at 02:35

0 Answers0