c# - EF access navigation properties in model -
i have entity 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, 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 permissions
list in haspermission
has 0 length, why , how solve?
this occurring because of entity framework lazy loading. in first statement, requesting permissions
property, causes entity framework generate query loads table database. in second query, asking entity framework load user
table database, haspermission
method calling has no way of making database call load permissions
table.
this common issue when working entity framework. can resolved using include()
extension method entity framework eagerly load related table in second query, i.e. user ur = db.user.where(u => u.userid == 1).include(u => u.role.permissions).first();
Comments
Post a Comment