比较对象int或dbnull.value linq [英] compare object int or dbnull.value linq
问题描述
我有一个linq查询:
I have a linq query:
var capacityQuery =来自mySQLDataTable.AsEnumerable()中的信息其中Info.Field< object>(位置")== Location.ID按Info.Field< DateTime>("date")
其中Info.Field("location")== Location.ID行是我遇到问题的地方
The line "where Info.Field("location") == Location.ID" is where I am having problems
我的问题是.如何在where语句中进行比较,该语句可能是DBNull.Value或任一侧的int值
My Question is. How do I do a comparison in the where statement that might be either a DBNull.Value or an int value on either side
以下仅供参考:
Location是一个自定义类.ID返回一个对象.
Location is a custom class. The ID returns an object.
private int? addressID;
public object ID {
get
{
if (addressID == null)
return DBNull.Value;
else
return addressID;
}
}
必须为DBNull的原因是因为它来自数据库.还可以从数据库中填写表".
The reason it has to be DBNull is because it is coming from a database. The "table" is also being filled in from a database.
我知道==在这种情况下是错误的,因为它比较的引用显然是错误的.
I know == in this case is wrong because its comparing the references which is obviously false.
我知道object.equal(var1,var2)应该可以工作,但是我猜不出来是因为它们是2个不同的对象.
I know object.equal(var1, var2) should work but it doesnt which im guessing is because they are 2 different objects.
在表端和类端的值都可以是int或DBNull.
The values could be an int or DBNull both on the table side and the class side.
这是在foreach循环中,因此我使用相同的查询,其中Location的值为int或DBNull的值.
This is in a foreach loop so I use the same query where Location has an int value or when it has a DBNull value.
我的问题是.如何在where语句中进行比较,该语句可能是DBNull.Value或任一侧的int值
Again My Question is. How do I do a comparison in the where statement that might be either a DBNull.Value or an int value on either side
推荐答案
使用
private int? addressID;
public object ID {
get
{
return addressID.HasValue ? addressID.Value as object : DBNull.Value;
}
}
相反.这样,如果addressID尚未初始化或故意将其设置为null,则ID属性将返回DBNull.Value.否则,它将返回一个 int,但您必须自己将它从 object 转换为 int 或 int?.
instead. This way, if addressID has not been initialized or if it has been deliberately set to null, the ID property will return a DBNull.Value. Otherwise, it will return an int, but you have to cast it yourself from object to int or int?.
话虽如此,作者将空值的创建称为十亿美元的错误",但现在我认为它已达到数万亿美元.您应该返回一个int吗?如果可以,请使用数据库中的数据类型,在这种情况下,比较将始终有效.我不确定您使用哪个ORM,但据我所知,Dapper和linq2db可以正确处理此方案.
Having said that, creation of the null has been called "a billion dollar mistake" by the author, but by now I think it is in the trillions. You should return an int? datatype from the database if you can, in which case, the comparison will always work. I am not sure which ORM do you use, but Dapper and linq2db handle this scenario correctly as far as I know.
这篇关于比较对象int或dbnull.value linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!