Search code examples
c#entity-frameworklinq-to-entities

How can I change the query to make result not equal to NULL


I use LINQ to the entity in my project. At some point I fetch data from database:

 int vectorLayerId = 5;
 int pointFeatId = 10;

 var RealValue = x.VectorLayer_FieldsValue
                  .Where(f=>f.FeatIdPointFeatures == vectorLayerId && f.VectorLayerFieldsId == pointFeatId)
                  .Select(v => new { v.Id, v.FieldValue })
                  .FirstOrDefault()

if in my database doesn't exist record that associated with a filter the RealValue object is set to NULL. While I need RealValue to be all properties Id zero and FieldValue property empty if the record that associated with the filter not exists.

How can I change the query above to make RealValue not to be NULL and properties Id and FieldValue zero and empty?


Solution

  • Try this:

    int vectorLayerId = 5;
    int pointFeatId = 10;
    
     var RealValue = x.VectorLayer_FieldsValue
                      .Where(f=>f.FeatIdPointFeatures == vectorLayerId && f.VectorLayerFieldsId == pointFeatId)
                      .Select(v => new { v.Id, v.FieldValue })
                      .FirstOrDefault() ?? new { Id = 0, FieldValue = "0"};
    

    This uses the null-coalescing operator (??) to return an anonymous type with a property Id and FieldValue (both set to 0) when the Linq query returns null.

    Incidentally, if you're using C# 7, you could also have your Linq query create a Tuple instead of an anonymous type, which might be easier if you need to return it in a function or something like that:

    int vectorLayerId = 5;
    int pointFeatId = 10;
    
     var RealValue = x.VectorLayer_FieldsValue
                      .Where(f=>f.FeatIdPointFeatures == vectorLayerId && f.VectorLayerFieldsId == pointFeatId)
                      .Select(v => (v.Id, v.FieldValue))
                      .FirstOrDefault() ?? (Id: 0, FieldValue: "0");