您定製的用戶類別應該是這樣的:
public class CustomizedUser : IdentityUser
{
public int OrgId {get; set;}
public DateTime JoinDate { get; set; }
//...
// and other simple fields
//Fields related to other tables
public virtual ICollection<Article> Articles { get; set; } = new List<Article>();
//...
}
而且你CustomizedApplicationDbContext類
public class CustomizedApplicationDbContext : IdentityDbContext<CustomizedUser>, IApplicationDbContext
{
public CustomizedApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static CustomizedApplicationDbContext Create()
{
return new CustomizedApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//your entity configurations go here if you have any
base.OnModelCreating(modelBuilder);
}
//These fields are neccessary in order to maintain the power of base class
public DbChangeTracker Changetracker => base.ChangeTracker;
public Database DatabBase => base.Database;
//your own dbsets go here except CustomizedUser, because the base class IdentityDbContext<CustomizedUser> handles it
public IDbSet<Article> Articles { get; set; }
//...
}
現在,請記住在代碼中使用CustomizedApplicationDbContext和CustomizedUser替換每個ApplicationDbContext引用(特別是在由mvc創建的ManageController中)。
從現在起,您可以輕鬆地訪問用戶表就像其他表:
var db = new CustomizedApplicationDbContext();
var user = db.CustomizedUsers.First(x=> x.OrgId == 10 || Email == "[email protected]");
而要獲取當前用戶ORGID,你可以使用這樣的事情(不包括查詢DB):
var currentUserOrgId = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId()).OrgId;
希望這是有幫助的
來源
2017-02-28 08:11:13
Efe
是您的ApplicationDbContext類從IdentityDbContext衍生 ??? –
Efe
@Efe是的,我相信。我是否必須查詢數據庫,或者是否使用身份對象,因爲我添加了屬性 – transformer
如果您繼承正確,U可以輕鬆地查詢數據庫。我以前做過這個。只要給我30分鐘發佈我爲你做的任何事情。我在去公司的路上 – Efe