简体   繁体   English

模型中的EF访问导航属性

[英]EF access navigation properties in model

I have an entity like below 我有一个像下面这样的实体

public class Role
{
    [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, StringLength(30)]
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<RolePermission> Permissions { get; set; }

    public bool HasPermission(String code)
    {
        foreach (var p in this.Permissions)
        {
            if (p.Permission.Code.Equals(code))
                return true;
        }

        return false;
    }
}

and in controller, this code run fine: 在控制器中,此代码运行良好:

for (var p in db.User.Where(u => u.UserId == 1).First().Role.Permissions) { PrintToDebug(); }

but: 但:

User ur = db.User.Where(u => u.UserId == 1).First();
ur.Role.HasPermission("Some_Code_Were_Defined");

then the Permissions list in HasPermission always has a zero length, why and how to solve? 那么HasPermissionPermissions列表始终为零,为什么以及如何解决?

This is occurring because of Entity Framework Lazy Loading. 这是由于实体框架延迟加载而发生的。 In your first statement, you are specifically requesting the Permissions property, which causes Entity Framework to generate a query that loads that table from the database. 在您的第一条语句中,您特别要求Permissions属性,这将导致Entity Framework生成一个查询,该查询将从数据库中加载该表。 In the second query, you are only asking Entity Framework to load the User table from the database, but the HasPermission method you are calling has no way of making another database call to load the Permissions table. 在第二个查询中,您仅要求Entity Framework从数据库中加载User表,但是您正在调用的HasPermission方法无法进行另一个数据库调用来加载Permissions表。

This is a common issue when working with Entity Framework. 在使用实体框架时,这是一个常见问题。 It can be resolved by using the Include() extension method from Entity Framework to eagerly load the related table in the second query, ie User ur = db.User.Where(u => u.UserId == 1).Include(u => u.Role.Permissions).First(); 可以通过使用Entity Framework中的Include()扩展方法来解决,以在第二个查询中迅速加载相关表,即User ur = db.User.Where(u => u.UserId == 1).Include(u => u.Role.Permissions).First();

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

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