简体   繁体   English

在Fluent Nhibernate中有一种流畅的方法来进行标准查询吗?

[英]Is there a fluent way to do criteria queries in Fluent Nhibernate?

Currently I create my criteria as follows: 目前,我创建标准如下:

gameCriteria = Restrictions.Eq("Name", videoGameName);

I was wondering if fluent nhibernate adds any features that allow something of the following: 我想知道流利的nhibernate是否添加了允许以下功能的任何功能:

gameCriteria = Restrictions.Eq<VideoGame>(v => v.Name, videoGameName);

In short, I want to remove the magic string . 简而言之,我想删除魔术字符串 (My actual queries tend to involve many magic strings which lead to errors due to typos and such.) (我的实际查询往往涉及许多魔术字符串,这些字符串会因错别字等导致错误。)

Just found the answer in the repository that another developer wrote. 刚刚在另一个开发人员编写的存储库中找到了答案。

gameCriteria = Restrictions.Eq(Projections.Property<VideoGame>(v => v.Name), videoGameName);

Now I feel silly for the time I spent searching for this. 现在,我花了很多时间在寻找这个问题上感到很傻。

There is a built in NHibernate class Restrictions.cs . 有一个内置的NHibernate类Restrictions.cs It provides this method: 它提供了这种方法:

/// <summary>
/// Build an ICriterion for the given property
/// </summary>
/// <param name="expression">lambda expression identifying property</param>
/// <returns>returns LambdaRestrictionBuilder</returns>
public static LambdaRestrictionBuilder On<T>(Expression<Func<T, object>> expression)
{
    ExpressionProcessor.ProjectionInfo projection = 
      ExpressionProcessor.FindMemberProjection(expression.Body);
    return new LambdaRestrictionBuilder(projection);
}

And we can use it like this: 我们可以这样使用它:

// exact match
Restrictions.On<VideoGame>(v => v.Name == videoGameName);

or 要么

// LIKE expression as 'videoGameName%'
Restrictions.On<VideoGame>(v => v.Name).IsLike(videoGameName, MatchMode.Start);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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