简体   繁体   English

实体框架不会加载导航属性

[英]Entity framework does not load navigation properties

I am using EF with POCO for one of my projects. 我将EF和POCO一起用于我的一个项目。

The data context and pocos have been created successfully and I can fetch the data. 数据上下文和pocos已成功创建,我可以获取数据。 There is one problem: the navigation properties are always null. 有一个问题:导航属性始终为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); 我通过简单的linq查询访问这些元素: Db.UserProfile.FirstOrDefault(f => f.Username == username); where Db is my datacontext. Db是我的数据上下文。

The whole user profile object will have data but the navigation property SecurityRole is always null. 整个用户配置文件对象将具有数据,但导航属性SecurityRole始终为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. 我认为EF代码首次工作的方式应该是在您的SecurityRole类上将Id属性设置为SecurityRoleId或其他内容,或对其应用[Key]属性。 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; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM