实体框架不加载导航属性
我在我的一个项目中使用 EF 和 POCO。
数据上下文和 pocos 已成功创建,我可以获取数据。有一个问题:导航属性始终为空。
我有这两个类:
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>();
}
}
数据库包含来自 userprofile 和 securityrole 的对象。外键已设置。我确实通过简单的 linq 查询访问这些元素: Db.UserProfile.FirstOrDefault(f => f.Username == username);
其中 Db
是我的数据上下文。
整个用户配置文件对象将包含数据,但导航属性 SecurityRole 始终为空。
我错过了什么吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 EF 代码首先工作的方式应该将您的 SecurityRole 类上的 Id 属性作为 SecurityRoleId 或其他内容,或者对其应用 [Key] 属性。那么它应该可以工作
或者
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
or