简体   繁体   中英

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?

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. 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.

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();

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.

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