English 中文(简体)
linq- to- sql 无效或默认
原标题:linq-to-sql null or default

我有一个这样的问题:

var TheQuery = (from....
               where x.TheDate >= StartDate && x.TheDate <= EndDate
               select new MyModel()
               {
                   Total = (int?)x.Count() ?? 0,
                   ....
               }).Single();

基本上, 我将查询基于两个日期之间的一些记录。 如果日期为 0 值, 则返回 0 作为总计。 但是, 如果根本没有值, 它返回无效和崩溃 。 我可以添加 < code>. SingleOrDefault () , 但返回为无效, 而不是 MyModel 以 0 为主 。 属性总计被定义为 int 。

我怎样才能解决这个问题?

谢谢 谢谢

最佳回答

计数有一个与上游值超载的超载, 当没有符合上游值的项目时返回 0

 var result = new MyModel {
                          Total = <yourDataSource>
                            .Count(x.TheDate >= StartDate && x.TheDate <= EndDate)
                          };
问题回答
if(TheQuery !=null || TheQuery .Count()>0){
 //do something you wanna do

时 时

 var v = TheQuery.ToList();

现在检查

if (v.Count > 0)

您应该选择:

int count = (from x in ...
where x.TheDate >= StartDate && x.TheDate <= EndDate
select c).Count();

这就是你想要的。

var TheQuery = (from....
               where x.TheDate >= StartDate && x.TheDate <= EndDate
               select new MyModel()
               {
                   Total = (int?)x.Count() ?? 0,
                   ....
               }).DefaultIfEmpty(0).Single() 




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签