我在Linq to NHibernate查询中通过多个字段进行排序时遇到问题.有没有人知道什么可能是错的或者是否有解决方法?
码:
IQueryable<AgendaItem> items = _agendaRepository.GetAgendaItems(location)
.Where(item => item.Minutes.Contains(query) || item.Description.Contains(query));
int total = items.Count();
var results = items
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
.ToArray();
return new SearchResult(query, total, results);
Run Code Online (Sandbox Code Playgroud)
我尝试用多个OrderBy调用替换ThenBy.结果相同.如果我注释掉两个ThenBy调用,该方法效果很好.
我收到的错误:
[SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.
Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
[ADOException: could not execute … Foo有头衔.
酒吧参考Foo.我有一个酒吧收藏.
我需要一个Foo.Title的集合.
如果我收集10个酒吧,我会称db 10次.
bars.Select(X => x.Foo.Title)
目前这个(使用NHibernate Linq并且我不想丢弃它)检索Bar集合.
var q = from b in Session.Linq<Bar>()
where ...
select b;
Run Code Online (Sandbox Code Playgroud)
我读了艾恩德对此的看法.
另一个相关问题.
一些文档.
和另一篇相关的博文.
也许这有用吗?
什么这个?
也许MultiQuery是我需要的?:/
但我仍然无法在适当的解决方案中"编译"这个.
如何避免选择n + 1?
nhibernate domain-driven-design fluent-nhibernate linq-to-nhibernate select-n-plus-1
场景:我有一个启用了延迟加载的客户对象.我在整个程序中使用它来调用列表框的客户列表.它与Division_Customer_Rel,Division_Email_Rel和Email_Address对象有关系.所有关系都有Lazy = true, Cascade = ManyRelationCascadeEnum.AllDeleteOrphan, Inverse = true.
问题:当我使用新会话并尝试保存时,会给我错误A different object with same identifier was already associated with the session.我试图通过加入调用中的其他对象来使用LINQ返回列表而不使用新会话,但我不确定如何在加入时使用ActiveRecordLinq <>.
private Customer GetCustomer()
{
return (from x in ActiveRecordLinq.AsQueryable<Customer>()
where x.Customer_ID == ((Customer)lst_customers.SelectedItem).Customer_ID
select x).First();
}
Run Code Online (Sandbox Code Playgroud)
产生错误的代码
using (new SessionScope())
{
//var sess = GetSession();
//var customer =
// sess.CreateCriteria<Customer>("c").CreateCriteria("c.DivisionCustomer_Rels").List<Customer>().
// First();
var customer = GetCustomer();
/* Ensure user wishes to commit the data. */
var result =
MessageBox.Show(
@"You are about …Run Code Online (Sandbox Code Playgroud) 我一直试图使用Linq到NHibernate获得不同的值,而且我失败了.
我试过了:
var query = from requesters in _session.Linq<Requesters>()
orderby requesters.Requestor ascending
select requesters;
return query.Distinct();
Run Code Online (Sandbox Code Playgroud)
以及
var query = from requesters in _session.Linq<Requesters>()
orderby requesters.Requestor ascending
select requesters;
return query.Distinct(new RequestorComparer());
Run Code Online (Sandbox Code Playgroud)
RequestorComparer的位置
public class RequestorComparer : IEqualityComparer<Requesters>
{
#region IEqualityComparer<Requesters> Members
bool IEqualityComparer<Requesters>.Equals(Requesters x, Requesters y)
{
//return x.RequestorId.Value.Equals(y.RequestorId.Value);
return ((x.RequestorId == y.RequestorId) && (x.Requestor == y.Requestor));
}
int IEqualityComparer<Requesters>.GetHashCode(Requesters obj)
{
return obj.RequestorId.Value.GetHashCode();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
无论我如何构造语法,它似乎永远不会出现.Distinct()..Distinct()默认情况下,在我查询的表中没有多个重复项,按照195条记录的顺序排列,但应该只返回22个不同的值.
我不确定我做错了什么,但非常感谢可以提供的任何帮助.
谢谢
这是否可以使用带有nhibernate linq的let关键字?我写
var posts = from post in postsRepository.GetPosts(name)
let commentsCount = (from c in NHUnitOfWork.CurrentSession.Linq<Comment>()
where c.Post.ID == post.ID
select c).Count()
select new ...
Run Code Online (Sandbox Code Playgroud)
作为回应我有
NHibernate.QueryException:无法解析属性:post:Sys.Domain.Entities.Post
我正在使用NHibernate 3.1.0,我试图通过使用BaseHqlGeneratorForMethod和扩展,DefaultLinqToHqlGeneratorsRegistry如Fabio的帖子中所解释的那样扩展LINQ提供程序.
例如,为了支持ToString()我创建了ToStringGenerator如下所示.
internal class ToStringGenerator : BaseHqlGeneratorForMethod
{
public ToStringGenerator()
{
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<object>(x => x.ToString())
};
}
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
return treeBuilder.Cast(visitor.Visit(targetObject).AsExpression(), typeof(string));
}
}
Run Code Online (Sandbox Code Playgroud)
我已经注册使用
internal class CustomLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public CustomLinqToHqlGeneratorsRegistry()
{
this.Merge(new ToStringGenerator());
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止这适用于"静态"查询,我可以像这样使用它:
var results = mSession.Query<Project>();
string pId = "1";
results = results.Where(p => p.Id.ToString().Contains(pId));
Run Code Online (Sandbox Code Playgroud)
这正确转换为SQL对应(使用SQL Server …
我有以下问题
基本上我有以下2个片段:
var contactAssociation =
session.QueryOver<ContactAssociation>(() => contactAssociationAlias)
.Where(() =>
contactAssociationAlias.Contact.ID == careGiverId &&
contactAssociationAlias.Client.ID == clientKey)
.Where(() =>
contactAssociationAlias.AclRole.RoleName == "Care Giver")
.SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
和
var contactAssociation = session.Query<ContactAssociation>()
.Where(cr =>
cr.Contact.ID == careGiverId
&& cr.Client.ID == clientKey)
.Where(cr =>
cr.AclRole.RoleName == "Care Giver")
.SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
第二个工作第一个输出此错误:
Message=could not resolve property: AclRole.RoleCode of:
SL.STAdmin.DAL.ContactAssociation
Run Code Online (Sandbox Code Playgroud)
有人知道为什么吗?先感谢您
我正在尝试在ASP.NET MVC 2应用程序中实现搜索功能.我根据用户输入的条件创建表达式:
public ViewResult FindCustomer( string forename, string familyname, DateTime? dob)
{
Expression<Func<Customer, bool>> searchCriteria = p => (
forename.IsNullOrEmpty() ? true : p.Forename == forename
&& familyname.IsNullOrEmpty() ? true : p.FamilyNames.Any(n => n.Name == familyname)
&& dob.HasValue ? true : p.DOB == dob
);
Run Code Online (Sandbox Code Playgroud)
然后传递给存储库中的方法
IQueryable<Customer> customers = CustomerRepository.FilterBy(searchCriteria);
Run Code Online (Sandbox Code Playgroud)
问题是当我运行它时,我得到以下异常
System.InvalidCastException: Unable to cast object of type 'NHibernate.Hql.Ast.HqlCast' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'
Run Code Online (Sandbox Code Playgroud)
根据这个问题,问题是在表达式中使用条件运算符.
所以我想我必须以其他方式创建Expression,但我不知道该怎么做.我对Linq很新,所以任何帮助都会被感激之情!
无论何时与这些记录相关联,我都希望从特定日期获取所有记录.到目前为止,我有这样的方法:
public IQueryable<Record> QueryByDay(DateTime day)
{
DateTime from = day.Date;
DateTime to = day.Date.AddDays(1);
return repository.Table
.Where(t => t.MyDate >= from && t.MyDate < to);
}
Run Code Online (Sandbox Code Playgroud)
但是在linq-to-object中我们可以做(假设Table现在是一些集合):
public IEnumerable<Record> QueryByDay(DateTime day)
{
return repository.Table
.Where(t => t.MyDate.Date == day.Date);
}
Run Code Online (Sandbox Code Playgroud)
这显然更具可读性,感觉更干净.我想知道是否有更好的方法来编写使用数据库存储和nhibernate的第一个方法?
拥有NHibernate实体:
Company,Invoice并且InvoiceLine具有小数属性Price.
A Company具有类型的集合Invoice,并且Invoice具有类型的集合InvoiceLine.
如何获取属于发票行的所有价格的总和,这些发票行属于由id指定的某个公司的发票?
我试着写这样的查询:
session
.Query<InvoiceLine>()
.Where(invoiceLine => invoiceLine.Invoice.Company.Id == companyId)
.Sum(invoiceLine => invoiceLine.Price);
Run Code Online (Sandbox Code Playgroud)
但它引发了一个例外:
NHibernate.Exceptions.GenericADOException
"Could not execute query[SQL: SQL not available]"
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
at NHibernate.Impl.AbstractSessionImpl.List(IQueryExpression queryExpression, QueryParameters parameters)
at NHibernate.Impl.ExpressionQueryImpl.List()
at NHibernate.Linq.DefaultQueryProvider.ExecuteQuery(NhLinqExpression nhLinqExpression, IQuery query, NhLinqExpression nhQuery)
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Sum[TSource](IQueryable`1 source, Expression`1 selector)
Run Code Online (Sandbox Code Playgroud)
内在异常:
System.ArgumentNullException
"Value cannot be null.\r\nParameter name: item"
at …Run Code Online (Sandbox Code Playgroud)