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 ?
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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.