NHibernate - 延迟加载问题 - 初始化 [] - 无法初始化代理 - 没有会话."} [英] NHibernate - LAZY LOADING PROBLEM -Initializing[]-Could not initialize proxy - no Session."}

查看:53
本文介绍了NHibernate - 延迟加载问题 - 初始化 [] - 无法初始化代理 - 没有会话."}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Fluent NHibernate,我对延迟加载有点困惑.

Hi I use Fluent NHibernate and I am little confusing with Lazy Loading.

  1. 我查询了数据库中的对象
  2. 修改对象属性
  3. 用这个对象更新数据库

代码如下:

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 配置类:

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();
    }
}

这里是用法:

    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();
                }
            }
        }
   }

问题代码:

var actualAccount = LoginDbHelper.GetAccount(nick);

//modify
actualAccount.Status.Msg = "New status 2";
actualAccount.Status.AddTime = DateTime.Now;


LoginDbHelper.SaveOrUpdateAccount(account);

我收到此错误:

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

堆栈跟踪:

 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()

我在谷歌上搜索它,我认为它是由延迟加载引起的,因为在方法 GetAccount 中我关闭了 SESSION.这是我第一次尝试使用 NHibernate 那么如何正确解决这个问题?如果是,可以禁用 LAZY LOADING 怎么办?

推荐答案

你说得对.因为 NHibernate Session 在您的 GetAccount 方法中关闭(它仅在 using 语句的范围内打开),所以您不能在此方法之外加载其他对象.有 2 个潜在的修复:

You are correct. Because the NHibernate Session is closed in your GetAccount method (it is only open in the scope of the using statement), you cannot load additional objects outside of this method. There are 2 potential fixes:

  1. 在操作级别(即在包含问题代码的方法中)创建会话,然后在 get & 中使用此会话.保存方法.您可以通过将会话作为参数传递给方法来使用会话.
  2. 将对象更改为不使用延迟加载.您可以通过将 .Not.LazyLoad() 添加到流畅映射中的 Status 对象来实现.
  1. Create the session at the operation level (i.e. in the method containing the problem code), then use this session in the get & save methods. You can use the session by passing it in as a parameter to the methods.
  2. Change the object to not use lazy loading. You can do this by adding .Not.LazyLoad() to the Status object in your fluent mapping.

这篇关于NHibernate - 延迟加载问题 - 初始化 [] - 无法初始化代理 - 没有会话."}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆