Solved

LINQ Entity Query Return Null Subtract Error?

Posted on 2014-01-02
8
1,538 Views
Last Modified: 2016-02-10
I have a simple LINQ Entiry query which returns null because NO table rows exist yet. I would like a more elegant code instead of the one I currently have working. Help.

var incomes = (from i in context.Incomes
                           where i.UserID == 101
                           group i by i.UserID into g
                           select new { Total = g.Sum(s => s.Amount) }).FirstOrDefault();

decimal incomesTotal = 0;
if (incomes != null)
{
    incomesTotal = incomes.Total;
}

MyViewModel model = new MyViewModel
{
    // totalDiff = (decimal?)incomes.Total ?? 0 - budget.Total,   // Not Working Solution

    totalDiff = incomesTotal - budget.Total
};
0
Comment
Question by:WorknHardr
  • 4
  • 4
8 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39751462
Why not simply:

MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .Sum(i => i.Amount)
};

Open in new window

0
 

Author Comment

by:WorknHardr
ID: 39751510
I still get an error if "Amount" is null.

Error: The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .Sum(i => i.Amount) - budget.Total
};

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39751540
Ah, I missed that detail. You can add one more call:

MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .Sum(i => i.Amount)
                       .DefaultIfEmpty() - budget.Total
};

Open in new window

0
 

Author Comment

by:WorknHardr
ID: 39751634
Hmm, still same error. This is the most difficulty I've experienced with LINQ. I had to place the DefaultIfEmpty differently because it doesn't exist the other way and still doesn't work.
MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .DefaultIfEmpty() //<--
                       .Sum(i => i.Amount) - budget.Total
};

Open in new window

0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39751688
Let's blame it on my sleep deprivation   ; )

What is the type of the Amount property?
0
 

Author Comment

by:WorknHardr
ID: 39751746
Okay making progress,...

1. changed 'totalDiff' to Nullable
2. added Nullable to query
3. added .GetValueOrDefault(0)
4. Works!
    - view returns $-2191.03 which is correct

public Nullable<decimal> totalDiff{ get; set; }

MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .Sum(i => (decimal?)i.Amount)
                       .GetValueOrDefault(0)
                      - budget.Total
};

[View]
@Model.totalDiff .Value.ToString("c")
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 400 total points
ID: 39751959
If the Amount property is itself nullable, then you could shorten that to:

MyViewModel model = new MyViewModel
{
    totalDiff = context.Incomes
                       .Where(i => i.UserID == 101)
                       .Sum(i => i.Amount ?? 0M)
                      - budget.Total
};

Open in new window

0
 

Author Closing Comment

by:WorknHardr
ID: 39754222
I like it, thanks again for great help :)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now