c# - 如何以引用为标准进行 NHibernate 查询?

标签 c# .net nhibernate

我正在尝试通过 NHibernate 进行查询,其中结果的标准取决于引用的表。我该怎么做呢?让我们看一个简单的例子:

public class Foo
{ 
    public int Id { get; set; }
    public string Name { get; set; }
    public Bar ReferencedBar { get; set; }
}    

public class Bar
{ 
    public int Id { get; set; }
    public string Name { get; set; }
}

然后将 Foo 映射到 Bar:

public class FooMapping : ClassMap<Foo>
{
    public FooMapping()
    {
        Id(c => c.Id).GeneratedBy.HiLo("1");
        Map(c => c.Name).Not.Nullable().Length(100);
        References(c => c.Bar);
    }
}

现在我想从数据库中获取所有引用特定 Bar 的 Foo。此函数使用 Criteria,但如果您认为更好,请给出使用其他内容的示例:

public IList<Foo> GetAllFoosReferencingBar(Bar bar)
{
    using (var tx = Session.BeginTransaction())
    {
        var result = Session.CreateCriteria(typeof(Foo))
            .Add(Restrictions./* foo.ReferencedBar == bar */) // <-- How to add restriction using reference? 
            .List<Foo>();
        tx.Commit();
        return result; 
    }
}

最佳答案

这实际上比人们想象的要容易。只需直接使用属性名称和对象向 critierion 添加一个 Equal 限制:

public IList<Foo> GetAllFoosReferencingBar(Bar bar)
{
    using (var tx = Session.BeginTransaction())
    {
        var result = Session.CreateCriteria(typeof(Foo))
            .Add(Restrictions.Eq("ReferencedBar", bar) // <--- Added restriction
            .List<Foo>();
        tx.Commit();
        return result; 
    }
}

关于c# - 如何以引用为标准进行 NHibernate 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2453095/

相关文章:

.net - 结构与类

nhibernate - JSON.NET 和 nHibernate 集合的延迟加载

c# - 使用 Nhibernate 静默插入失败

c# - 我可以用 ASP.NET 页面类中的私有(private)变量替换 HiddenField 吗?

c# - 如何在 Entity Framework 中使用 LINQ-to-SQL 回滚事务?

nhibernate - 对子类的 HQL 查询

.net - 流畅的 NHibernate : Version column should NOT be used for concurrency

c# - 自定义身份验证中间件 - 如何检查请求是匿名的还是授权的?

c# - 从 wcf 绑定(bind) transferMode 从 "Buffered"更改为 "Streamed"是否被视为客户端的重大更改?

c# - 在 dll 库中显示消息框