Reputation: 6089
I am using EF with POCO for one of my projects.
The data context and pocos have been created successfully and I can fetch the data. There is one problem: the navigation properties are always null.
I've got these two classes :
public class UserProfile {
public string Username { get; set; }
public int RoleId { get; set; }
public virtual SecurityRole SecurityRole { get; set; }
}
public class SecurityRole {
public int roleId { get; set; }
public string RoleDescription { get; set; }
}
public class DataContext : ObjectContext {
public ObjectSet<UserProfile> UserProfiles { get; set; }
public ObjectSet<SecurityRole> SecurityRoles { get; set; }
public DataContext() : base("name=datacontext_entities", "datacontext_entities") {
UserProfiles = CreateObjectSet<UserProfile>();
SecurityRole = CreateObjectSet<SecurityRole>();
}
}
The database contains objects from userprofile and securityrole. The foreign keys are set. I do access those elements by the simple linq query : Db.UserProfile.FirstOrDefault(f => f.Username == username);
where Db
is my datacontext.
The whole user profile object will have data but the navigation property SecurityRole is always null.
Am I missing something ?
Upvotes: 0
Views: 951
Reputation: 361
I think the way EF code first works you should have the Id property on youur SecurityRole class as SecurityRoleId or something or apply a [Key] attribute to it. It should work then
public class SecurityRole
{
[Key]
public int roleId { get; set; }
public string RoleDescription { get; set; }
}
or
public class SecurityRole
{
public int SecurityRoleId { get; set; }
public string RoleDescription { get; set; }
}
Upvotes: 1