NHibernate - LOSE DOWNLOAD - Initialization [] - Failed to initialize proxy - no session. "}

Hi, I am using Fluent NHibernate and I am a little confused with Lazy Loading.

  • I requested an object in the database
  • changed object properties
  • update the database using this object

Here is the code:

public class Credentials { public virtual int Id { get; set; } public virtual string Nick { get; set; } public virtual string Password { get; set; } } public class CredentialsMap : ClassMap<Credentials> { public CredentialsMap() { Id(x => x.Id); Map(x => x.Nick).Column("NICK"); Map(x => x.Password).Column("PASSWORD"); Table("R_CREDENTAILS"); } } public class Status { public virtual int Id { get; set; } public virtual string Msg { get; set; } public virtual DateTime AddTime { get; set; } } public class StatusMap : ClassMap<Status> { public StatusMap() { Id(x => x.Id); Map(x => x.Msg).Column("MESSAGE"); Map(x => x.AddTime).Column("ADD_TIME"); Table("R_STATUS"); } } public class Account { public virtual int Id { get; set; } public virtual string SelfNick { get; set; } public virtual Credentials Credentials { get; set; } public virtual Status Status { get; set; } } public class AccountMap : ClassMap<Account> { public AccountMap() { Id(x => x.Id); Map(x => x.SelfNick).Column("SELF_NICK"); References(x => x.Credentials) .Column("CREDENTIALS_ID") .ForeignKey(); References(x => x.Status) .Column("STATUS_ID") .ForeignKey(); Table("R_ACCOUNTS"); } } 

NHibernate configuration class:

 public class NHiberanteHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) InitializeSessionFactory(); return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString( @"Server=TEST\SQLEXPRESS;Database=SimpleNHibernate;Trusted_Connection=True;"). ShowSql() ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Account>().Conventions.Add( DefaultCascade.All())) .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true)) .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } 

Here is the usage:

  public class LoginDbHelper { public static Account GetAccount(string nick) { using (var session = NHiberanteHelper.OpenSession()) { var account = (session.QueryOver<Account>() .JoinQueryOver<Credentials>(a => a.Credentials) .Where(c => c.Nick == nick)); if (account != null) return account.SingleOrDefault(); return null; } } public static void SaveOrUpdateAccount(Account account) { using (var session = NHiberanteHelper.OpenSession()) { using (var trans = session.BeginTransaction()) { session.SaveOrUpdate(account); trans.Commit(); } } } } 

Problem Code:

 var actualAccount = LoginDbHelper.GetAccount(nick); //modify actualAccount.Status.Msg = "New status 2"; actualAccount.Status.AddTime = DateTime.Now; LoginDbHelper.SaveOrUpdateAccount(account); 

I get this error:

 {"Initializing[NHibernateSample1.Status#1]-Could not initialize proxy - no Session."} 

Stacktrace:

  at NHibernate.Proxy.AbstractLazyInitializer.Initialize() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Proxy\AbstractLazyInitializer.cs:line 113 at NHibernate.Proxy.AbstractLazyInitializer.GetImplementation() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Proxy\AbstractLazyInitializer.cs:line 191 at NHibernate.ByteCode.Castle.LazyInitializer.Intercept(IInvocation invocation) in d:\CSharp\NH\NH\nhibernate\src\NHibernate.ByteCode.Castle\LazyInitializer.cs:line 61 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.StatusProxy.set_Msg(String value) at NHibernateSample1.Program.Main(String[] args) in E:\C# PROJECTS\Samples\SimpleNHibernateClient\NHibernateSample1\Program.cs:line 215 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 

I am google and I think it is called Lazy Loading because in the GetAccount method I close SESSION. This is my first attempt with NHibernate, so HOW CAN I SOLVE THIS PROBLEM CORRECTLY? Is it possible to disable LAZY LOADING, if YES, how to do it?

+4
source share
3 answers

You're right. Since the NHibernate session is closed in the GetAccount method (it is open only as part of the using statement), you cannot load additional objects outside of this method. There are 2 possible fixes:

  • Create a session at the operation level (i.e., in the method containing the problem code), then use this session in the get and save methods. You can use a session by passing it as a parameter to methods.
  • Modify the object so as not to use lazy loading. You can do this by adding .Not.LazyLoad() to the Status object in your smooth display.
+6
source

I believe that the easiest way to disable lazy loading is to add a default Lazy convention, i.e.:

 .Conventions.Add( DefaultCascade.All(), DefaultLazy.Never() ) 

Please note that enabling lazy loading (DefaultLazy.Always ()) can really improve performance, depending on your application.

The downside is that you always need to open a session so that you can be lazy to load the rest of the data into the entity. In my experience, session management to support lazy loading is one of the big pain points with NHibernate.

+4
source

You open and close a session in the LoginDbHelper.GetAccount (...) method.
Try to create and open a session outside the method and pass it as a parameter to the method, for example:

  // method public static Account GetAccount(string nick, ISession session) { var account = (session.QueryOver<Account>().JoinQueryOver<Credentials>(a => a.Credentials).Where(c => c.Nick == nick)); if (account != null) return account.SingleOrDefault(); return null; } // usage var actualAccount = LoginDbHelper.GetAccount(nick); actualAccount.Status.AddTime = DateTime.Now; using (var session = NHiberanteHelper.OpenSession()) LoginDbHelper.SaveOrUpdateAccount(account, session); 
0
source

All Articles