4

Possible Duplicate:
Equivalent of SQL ISNULL in LINQ?

I am recently migrated from ADO.Net to Entity Framework

I have problem in executing this query in Linq

select IsNull(MAX(InvoiceNo),0) from Sales

I have written this query in LINQ except isNull()

        var q = (from p in dbContext.Sales
                 select p.InvoiceNo).Max();

But i dont know how to use IsNull() in this Linq

When i execute this Linq Query I am getting this exception.

'The invocation of the constructor on type 'JIMS.ViewModel.Transaction.SalesViewModel' that matches the specified binding constraints threw an exception.' Line number '8' and line position '6'.

I am using WPF MVVM FrameWork with Entity FrameWork as DAL

Community
  • 1
  • 1
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154

3 Answers3

9
var InvoiceNo = dbContext.Sales.Max(x => (int?)x.InvoiceNo) ?? 0;
Magnus
  • 45,362
  • 8
  • 80
  • 118
3

Try this:

var q = (from p in dbContext.Sales
                 select (int?)p.InvoiceNo).Max();
Kyberias
  • 1,263
  • 1
  • 14
  • 23
0

You will have to selectzero if invoicno is null. One way you could do this would be:

var elements = (from p in dbContext.Sales
                 where p.InvoiceNo != null
                 select p.InvoiceNo).Max();

Assuming there'll always be at least one invoiceno if not you can do

var elements = (from p in dbContext.Sales
                 select p.InvoiceNo ?? 0).Max();

which will have to compare all elements so it could be slower than the first approach

Rune FS
  • 21,497
  • 7
  • 62
  • 96