I have an object User which references an object State. The foreign key is a string of StateID and is optional. A user is not required to reference a State. I have the classes defined as follows
public class User
{
public int UserID {get; set'}
public string StateID {get; set;}
//some other properties
public virtual State State {get; set;}
}
public class State
{
public string StateID {get; set;}
//other properties
public ICollection<User> Users {get; set;}
}
When I try to do a linq query to get some users and their states, the State object is always null. I do get the StateID of my User of course so I know that is set properly.
My query looks like this:
var users = userRepo.where(x => x.StateID != null);
Also tried adding .ToList() to get the lazy load to execute which does not work either.
I have tried adding [key] annotation to StateID in State with no luck.
i have also tried giving up on lazy loading and using include("State") in my query also with no luck.
Any clues as to what I am doing wrong?
UPDATE I have also tried to explicitly specify the mapping as follows:
modelBuilder.Entity<User>()
.HasOptional(t => t.State)
.WithMany(b => b.Users)
.HasForeignKey(t => t.StateID);
Statetable?StateIDis a foreign key. Can you show your mapping configuration?IncludeandToList()I'd certainly expectStateto be loaded (and lazy loaded withoutInclude). Are you absolutely sure that the keys match? (No leading or trailing spaces, case issues)