我运行时遇到异常:Unrecognised method call in epression a.B.Count()
:
var query = session.QueryOver<A>()
.Where(a => a.B.Count() > 0)
.List();
以下代码有效:
var query1 = session.QueryOver<A>().List();
var query2 = query1.Where(a => a.B.Count() > 0);
有什么想法吗?感谢。
修改
这是我的映射。我正在使用NHibernate 3.1.0.4000:
型号:
public class A
{
public virtual int Id { get; private set; }
public virtual ICollection<B> Bs { get; set; }
}
public class B
{
public virtual int Id { get; private set; }
}
映射:
public class AMappings : ClassMap<A>
{
public AMappings()
{
Id(x => x.Id);
HasMany(x => x.Bs).LazyLoad();
}
}
public class BMappings : ClassMap<B>
{
public BMappings()
{
Id(x => x.Id);
}
}
我的其余代码:
class Program
{
static void Main(string[] args)
{
// Create connection string
string connectionString = new System.Data.SqlClient.SqlConnectionStringBuilder()
{
DataSource = @".\r2",
InitialCatalog = "TestNHibernateMappings",
IntegratedSecurity = true
}.ConnectionString;
// Create SessionFactory
ISessionFactory sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008.ConnectionString(connectionString)
.ShowSql())
.Mappings(m => m.FluentMappings
.Add(typeof(AMappings))
.Add(typeof(BMappings)))
.ExposeConfiguration(BuildSchema)
.BuildConfiguration()
.BuildSessionFactory();
// Test
var session = sessionFactory.OpenSession();
// This line works OK
var query1 = session.Query<A>()
.Where(a => a.Bs.Count() > 0);
// This line throws exception: Unrecognised method call in epression a.Bs.Count()
var query2 = session.QueryOver<A>()
.Where(a => a.Bs.Count() > 0);
}
static void BuildSchema(Configuration cfg)
{
new SchemaExport(cfg).Create(false, true);
}
}
答案 0 :(得分:4)
QueryOver不是LINQ。
您的第二个代码段有效,因为它检索所有记录并在内存中使用LINQ到对象。
你应该做的是:
session.Query<A>()
.Where(a => a.B.Count() > 0)
.ToList();
或更好:
session.Query<A>()
.Where(a => a.B.Any())
.ToList();
Query
是一种扩展方法,您需要添加using NHibernate.Linq;