很多关系集合没有加载

时间:2016-11-21 08:53:28

标签: c# collections many-to-many entity

我有课程:

  • 静态课程
  • 公共类MyContext
  • 公共类用户
  • 公共课权限
  • 公共静态类LocalStorage
  • public enum List item

以下是每个代码:

        static class Program {
            static void Main() {
                Permissions p = new Permissions() { PermissionName = Permission.ReadUser } ;
                User mirian = new User() { UserName = "miri", Password="123", PasswordChanged=true, Permissions = new List<Permissions>() {} };
                mirian.Permissions.Add(p);
                using (var db = new MyContext()) {
                     db.Permissions.Add(p);
                     db.Users.Add(mirian);
                     db.SaveChanges();
                }
            }
        }

        public class MyContext : DbContext {
            public MyContext() : base("AppEntityDB") {
                System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
            }
            public virtual DbSet<User> Users { get; set; }
            public virtual DbSet<Permissions> Permissions { get; set; }
        }

        public class User : BaseCore {
                MyContext _db = new MyContext();
                [Key]
                public int ID { get; set; }
                [MaxLength(20)]
                public string UserName { get; set; }
                public ICollection<Permissions> Permissions { get; set; }

                public bool Login(string username, string password) {
                  using (_db) {
                    var _userlist = _db.Users.Where(c => c.IsActive == true
                                             && c.UserName == username
                                             && c.Password == password).SingleOrDefault();
                    if (_userlist != null) {
                       LocalStorage.CurrentUser = _userlist;
                       return true;
                    }
                    return false;
                  }
               }
        }

        public class Permissions : BaseCore {
            [Key]
            public int ID { get; set; }

            public Permission PermissionName{ get; set; }

            public ICollection<User> User { get; set; }
       }

public enum Permission : byte {
        ManageAccounts = 0,
        ReadUser = 1,
        WriteUser = 2,
        ReadProduct = 3,
        WriteProduct = 4,
    }

    public static class LocalStorage {
        public static User CurrentUser { get; internal set; }
    }

登录时我调用User.Login()方法将LocalStorage.CurrentUser分配给从实体+ linq取得的当前用户对象。

当我调用LocalStorage.CurrentUser.Permissions时,我希望它返回一个拥有当前用户的权限列表。但它的值为null

任何线索?

1 个答案:

答案 0 :(得分:1)

我不确定但它可能是lazy loading而且它不是加载相关的实体。