简体   繁体   中英

How to convert this Lambda Expression in NHibernate Criteria

I have this class

public class MyClass
{
    public int Id { get; set;}
    public string Name { get; set; }
    public IList<MyClass> Classes { get; set; }
}

I am using Fluent NHibernate, and I have this AutoMappingOverride:

    public void Override(AutoMapping<MyClass> mapping)
    {
        mapping.HasManyToMany(m => m.Classes)
            .ParentKeyColumn("ClassId")
            .ChildKeyColumn("SecondClassId")
            .Table("ClassesRelation")
            .Cascade.SaveUpdate();
    }

And I have this method on my Repository:

    public IList<MyClass> ClassesThatContains(MyClass @class)
    {
        //allClasses.Where(tempClass => tempClass.Classes.Contains(@class))
        string query = string.Format(@"SELECT Class.* FROM Class WHERE Class.Id IN (SELECT ClassesRelation.ClassId FROM ClassesRelation WHERE ClassesRelation.SecondClassId = {0})", @class.Id);

        var criteria = NhSession.CreateSQLQuery(query).AddEntity(typeof(MyClass));

        return criteria.List<MyClass>();
    }

In the method ClassesThatContains I have the comment that is equivalent to SQL Statement, but NHibernate dont know Contains Linq method....So I used SQL Statement, but how can I convert this SQL Statement to Criteria like?

Obs: ClassRelation is not a Class.

Nhibernate has a linq provider in version 3 built in and as an addon in version 2. You could just change the method like so::

from c in session.Query<MyClass>()
from cr in session.Query<ClassRelation>()
where c.FirstId == cr.Id
where cr.SecondId = @class.Id
select c.Id;

Or something more closer to your query you actually want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM