LINQ is very useful, but it was also cause of my problems. I think almost everybody already have seen this exception: System.NullReferenceException: Object reference not set to an instance of an object. You can google it and I think you would find many useful information :) But it was not useful for me at all. I was stuck for some hours with this error message.
The reason was simple. Before some months ago I created application with connect to database and I was using LINQ to querying. I made some simple query like this:
var query = from table in sql08.minussevenshorts
where table.DATUM == yesterday
group table by table.order into g
select new
{
FirstColum = g.Key,
CountOfOrders = (g.Sum(p => p.MONEY) / g.Sum(p => p.STUFFS)),
};
everything works fine so I was satisfied at the moment. But after some months the error occurred and I didn't know reason at all. I checked my source code and database was only place where could be a problem. As I thought this really was cause of error because if you look at CountOfOrders column, there is not any condition which prevent before dividing by zero. When I was programming application I didn't even expecting that g.Sum(p => p.STUFFS) could return zero but data was changed when time goes by. I added simple condition and everything works fine now. Here it is:
CountOfOrders = (g.Sum(p => p.STUFFS) == 0 ? 0 : g.Sum(p => p.MONEY) / g.Sum(p => p.STUFFS)),
So this really was lesson for me. You should not trust that data will be same as you are expecting it. So check it all the time ;) I think if you need to make more counting operations, it is better to make your own class and work with raw data from database. But I am not sure what would be faster if you need just ordinary counting operations as I showed above. I think in that case is better to count inside querying.
I hope that maybe it would help somebody :)
No comments:
Post a Comment