Ne arayalım?

ARAMIZA KATILIN

BİZE ULAŞIN

Adres:

E-posta:

host/bin/bilisimlife.dll

iletisim@bilisimlife.net




 
Rserit
Developer
       
 1026  
 278

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

Selamlar,
Entitiy Framework'te SUM metodunu yaptırdığınızda eğer count 0 dönerse hata verir. Tam da "The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type generic parameter or the query must use a nullable type" hatasını alırsınız.

Çözüm yöntemi 1: DefaultIfEmpty metodunu kullanın.
Örnek:


db.Leads.Where(l => l.Date.Day == date.Day
            && l.Date.Month == date.Month
            && l.Date.Year == date.Year
            && l.Property.Type == ProtectedPropertyType.Password
            && l.Property.PropertyId == PropertyId)
         .Select(l => l.Amount)
         .DefaultIfEmpty(0)
         .Sum();


Yani Sum'dan önce kontrolü yaptırıyoruz. Haliyle 0 dönerse bile 0 yazdıracak.

Çözüm yöntemi 2: Casting yaptırın.
Örnek:


double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                                      && l.Date.Month == date.Month
                                      && l.Date.Year == date.Year
                                      && l.Property.Type == ProtectedPropertyType.Password
                                      && l.Property.PropertyId == PropertyId)
                          .Sum(l => (double?) l.Amount) ?? 0;


Sum metoduyla ?? operatörü kullanılırsa 0 count gelse bile 0 yazacaktır.

Referanslar: Stackoverflow


Iyi çalışmalar,
Recep.

Developer.


 
Rserit
Developer
       
 1026  
 278

Bu arada, DefaultIfEmpty şu şekilde kullanılıyor:

Kendi projemden bir örnek kod:


 var sumCost = Entities.PriceDefinition.Where(res => res.IsActive == true && res.IsDeleted == false

                         && res.CreatedOn >= startOfDay
                         && res.CreatedOn <= endOfDay
                             && res.BuyingCurrencyId == CurrencyId

                       ).Select(x => x.Buying).DefaultIfEmpty(0).Sum();


Normalde SUM metodunun içinde hesaplayacağım sütunu yazardım. Ancak DefaultIfEmpty kullanmadan önce Select kullanıp, hangi sütunu hesaplattıracaksam onu çağırıyorum. Haliyle tek sütun olduğu için SUM içerisine bir şey yazmam gerekmiyor. Böylece DefaultIfEmpty(0) yazdığımda direk Buying değerini alıyor.

Birçok kişi hata aldığı için bildirmek istedim.



Mesaj 22.07.2016 10:27:14 tarihinde Rserit tarafından düzenlenmiştir.

Developer.