Linq to NHibernate - 在select中作为值变量

时间:2016-12-12 10:54:56

标签: linq nhibernate

我们如何在LinqToNH查询中使用变量作为属性值?

我试过这个:

public class ValuesController : ApiController
{
    public string Get(int myId)
    {
        using (var session = NhHelper.OpenSession())
        {
            var test = new Test { Created = DateTime.Now.ToString() };
            var result = session.Query<Table>()
                .Where(x => x.Id == myId)
                .Select(x => new Table
                {
                    Id = x.Id,
                    TestProperty = test, //is always set to the first value (creation date is equal to value from the first execution)
                })
                .ToList();
            NhHelper.CloseSession();
        }

        return "value";
    }   
}

问题是此代码仅适用于第一次。第二个请求(具有不同的“myId”值)提供正确的SQL查询,但TestProperty的值仍然是旧的。它等于第一个请求的值。

它是RestApi Web应用程序,NH配置了Fluent。我为测试用例做了简单的帮助:

public static class NhHelper
{
    public static ISessionFactory SessionFactory { get; } = CreateSessionFactory();


    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012.ConnectionString(@"SERVER=myserver; DATABASE=MyDb; Integrated Security=SSPI;").ShowSql())
            //.ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
            .CurrentSessionContext<WebSessionContext>()
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Table>())
            .BuildSessionFactory();
    }

    public static ISession OpenSession()
    {
        if(!CurrentSessionContext.HasBind(SessionFactory))
        {
            CurrentSessionContext.Bind(SessionFactory.OpenSession());
        }

        return SessionFactory.GetCurrentSession();
    }

    public static void CloseSession()
    {
        if (!CurrentSessionContext.HasBind(SessionFactory))
            return;

        var currentSession = CurrentSessionContext.Unbind(SessionFactory);    
        //currentSession.Dispose();        
    }
}

0 个答案:

没有答案