wpf 如何将 DBNull 检入 linq 或 int32?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16009471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check DBNull into linq or int32?
提问by ujjaval
I want to fetch all the rows where CategoryIdis null. I write the following code but it gives me error
我想获取所有行 where CategoryIdis null。我写了下面的代码,但它给了我错误
" Operator ' == ' can not applied to operands of type 'int?' and System.DBNull
" 运算符 ' == ' 不能应用于类型为 'int?' 的操作数?和 System.DBNull
public Nullable<Int32> CategoryId { get; set; }
Game objGame;
var query = (from gametypebygametype in db.GameByGameTypes.Where(x => x.CategoryId == DBNull.Value)
join game in db.Games
on gametypebygametype.GameId equals game.GameId into joined
from game in joined.DefaultIfEmpty()
select new
{
game.GameId,
game.GameName
}
).Distinct();
List<Game> objlistGame = new List<Game>();
foreach (var item_temp in query)
{
objGame = new Game();
objGame.GameId = item_temp.GameId;
objGame.GameName = item_temp.GameName;
objlistGame.Add(objGame);
}
回答by Chris
Try just using nullrather than DBNull.Value, or HasValue = false.
尝试只使用null而不是DBNull.Value, 或HasValue = false。
回答by Habib
You need to modify your WHEREclause and use Nullable<T>.HasValueas:
您需要修改您的WHERE条款并Nullable<T>.HasValue用作:
.Where(x => !x.CategoryId.HasValue)
from
从
.Where(x => x.CategoryId == DBNull.Value)
回答by Sergey Berezovskiy
If you want to fetch all the rows where CategoryIdis null, then simply check if nullable has value assigned:
如果要获取CategoryIdis 的所有行null,则只需检查 nullable 是否已分配值:
db.GameByGameTypes.Where(x => !x.CategoryId.HasValue)

