1

In simple words, Is there a better way for my code? (check code below).

Detail:
In LINQ to SQL, I have a query that contains some inner query. In that inner query i used FirstOrDefault() so now i want to check if FirstOrDefault() returned any null value then i can access property.

var Bills = db.BillMasters.Select(x => new BillHomeViewModel {
            ConsumerCategory = db.ConsumerCategories.FirstOrDefault(c => c.ID == x.ConsumerCategory) == null ? String.Empty : db.ConsumerCategories.FirstOrDefault(c => c.ID == x.ConsumerCategory).CategoryName                
        });

1 Answers1

4

You can use DefaultIfEmpty to avoid ternary operator unsupported by entity framework

var Bills = db.BillMasters
.Select(x => new BillHomeViewModel
{
    ConsumerCategory = db.ConsumerCategories
        .Where(c => c.ID == x.ConsumerCategory)
        .Select(c => c.CategoryName)
        .DefaultIfEmpty("")
        .FirstOrDefault()
});
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • linq-to-sql. and First() is not supported in that case. DefaultIfEmpty works perfectly and only FirstOrDefault() works – Perfect28 Jan 21 '19 at 10:05
  • Strange, because the documentation says that `First` is supported(well, it's not mentioned on the list of unsupported) and that `DefaultIfEmpty(arg)` is not supported. I can't check. But since docs are from 2011 they might be outdated – Tim Schmelter Jan 21 '19 at 10:06
  • Error occurred: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead. Had to use FirstOrDefault() at the end. Now it works – Ashran Haider Jan 21 '19 at 10:06
  • @AshranHaider You should update it to FirstOrDefalut(), see the answer please – Perfect28 Jan 21 '19 at 10:06
  • @Ksv3n yes i did it as it was obvious in that error message. I just tell that in comments so that people will know about this error. – Ashran Haider Jan 21 '19 at 10:08