2016-01-20 20 views
2

我已將Identity Entity Framework項目調整爲NHibernate版本。現在我有一個ApplicationUser類是這樣的:如何確定在執行時如何生成NHibernate實體密鑰?

public class ApplicationUser : IdentityUser<TKey> 
{ 
    // TODO Auto determine if Id must be generated here or at DB. 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, TKey> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 

     // Add custom user claims here 
     return userIdentity; 
    } 
} 

在我目前的項目中,我們使用int鍵的一切,通過在數據庫Identity領域的支持。在這種情況下,我寧願該方法生成一個負的int臨時ID,而不是使用manager.CreateIdentityAsync,但如果我通常使用Identity,並且typeof(TKey)string,我希望此方法正常工作。

但是,注意,我並不關心id的類型,但是我是否必須在我的應用程序中生成它,或者數據庫是否會爲我生成它,這就是我想要在運行。

回答

0

您需要可以使用SessionFactory得到標識符生成:

var generator = ((ISessionFactoryImplementor)Session.SessionFactory) 
    .GetIdentifierGenerator(typeof(TEntity).FullName); 

if (generator is Assigned) 
{ 
    // Generate the identifier 
} 
+0

精彩。我只是在兩週前開始使用NHibernate,並發現它與EF 6相比笨拙,但每次我學習這樣的東西時,我都會更喜歡它。謝謝。 – ProfK