gpt4 book ai didi

c# - 在 LINQ-to-NHibernate 或 LINQ 中比较枚举时有什么考虑吗?

转载 作者:行者123 更新时间:2023-11-30 18:09:37 25 4
gpt4 key购买 nike

在这样的查询中:

var q = from l in session.Linq<Letter>()
where
letterTypeSearch == null ? true :
(l.LetterType.ToString() == letterTypeSearch)

l.LetterType 是一个枚举。

更新在当前的 linq-to-nhibernate 中比较枚举似乎是不可能的。虽然 letterTypeSearch 是一个包含 LetterType 实例的字符串,该实例是 ToString()ed 并且 LetterType 是从 int 继承的,有3种比较方式:

1- 在 String 中进行比较:这是不可能的,因为 l.LetterType.ToString() 会产生“(ArgumentOutOfRangeException):索引超出范围。必须为非负数并且小于集合的大小。参数名称:index, "error.

2- 比较 Enum (LetterType) 本身:这也是不可能的,因为 l.LetterType == LetterType.Internal 导致“(QueryException):NHibernate.Criterion.SimpleExpression 中的类型不匹配:LetterType 预期类型 System.Int32,实际类型 Faraconesh.EnterpriseAppUnits.OfficeAutomation.BusinessEntities.LetterType,"错误。

3- 在 Int32 中比较:然而不可能,因为 Convert.ToInt32(l.LetterType) 生成“(NotImplementedException): ToInt32 方法未实现。, "错误。

那么我如何比较 LINQ-to-NHibernate 中的枚举?这个问题是 LINQ-to-NHibernate 特有的还是所有 LINQ 用户都有这样的问题?

更新2这里是类,枚举和映射(smmarized):

    public class Letter
{
private LetterType _letterType;
public LetterType LetterType
{
set
{
_letterType = value;
}//end
get
{
return _letterType;
}//end
}
}

=========

公共(public)枚举 LetterType{ 传入 = 0, 传出= 1, 内部 = 2,

=========

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class
name="Faraconesh.EnterpriseAppUnits.OfficeAutomation.BusinessEntities.Letter,Faraconesh.EnterpriseAppUnits.OfficeAutomation.BusinessEntities"
table="OfficeAutomation_Letter">

<property
name="LetterType" column="LetterType"
type="int" update="true" insert="true" access="property"
not-null="true"/>

</class>
</hibernate-mapping>

最佳答案

您已将枚举映射为 type="int",这会导致错误,可能是因为没有与 int 之间的隐式转换。如果删除 type 属性,枚举将映射到数据库中的一个 int 值,Linq 查询将起作用。

另请注意,在您的属性映射中,除了名称和类型之外的每个属性都是不必要的,因为它们指定了默认值。 “名称”是属性映射中唯一必需的属性,请参阅第 property 节在引用文档中。

<property name="LetterType" />

使用最新 (2.1.2GA) 版本的 NHibernate.Linq,可从 nhforge.org 上的 NHibernate Core 下载链接获得。 , 以下枚举查询按预期工作。

var q = from l in session.Linq<Letter>()
where l. LetterType == LetterType.A4
select l;
var result = q.ToList<Letter>();

LetterType? ltype = LetterType.A4;
q = from l in session.Linq<Letter>()
select l;
if (code != null) {
q = q.Where( l => l.LetterType == ltype.Value );
}
result = q.ToList<Letter>();

但是,如果 ltype 为 null,则最后一个查询的这种形式将不起作用,因为查询解析器仍将尝试使用 ltype.Value。

q = from l in session.Linq<Letter>()
where ltype != null && l => l.LetterType == ltype.Value
select l;
result = q.ToList<Letter>();

关于c# - 在 LINQ-to-NHibernate 或 LINQ 中比较枚举时有什么考虑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2346537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com