Default Values ​​in LINQ Query

I have the following Linq query / function in an MVC3 application.

public AuditTrail GetNamesAddressesEmployers(long registryId , int changedField) { var otherNameAndAddress = (from a in context.AuditTrails where a.ChangedField == changedField && a.RegistryId == registryId select a).FirstOrDefault(); return otherNameAndAddress; } 

I want if otherNameAndAddress = null, then some values ​​should be assigned to its properties.

otherNameAndAddress has a Name and description property. This GetNamesAddressesEmployers is used in 3 places. I want to assign different values ​​for the name and description when otherNameAndAddress = null in all three places.

+4
source share
2 answers

You are already using FirstOrDefault (), so why not specify a default value:

 public AuditTrail GetNamesAddressesEmployers(long registryId, int changedField) { return context.AuditTrails .Where(a => a.ChangedField == changedField && a.RegistryId == registryId) .DefaultIfEmpty(new AuditTrail { /* fill properties here */ }) .FirstOrDefault(); } 
+4
source

Well, you can change the return statement to:

 return otherNameAndAddress ?? new AuditTrail { Name = "Default", Description = "Default }; 

or something like that ... but you say you want to assign different default values ​​for different calls. This means that you need to either pass the default value or default (for example, in the same way, using the operator with zero coalescing) on ​​the call site.

For instance:

 public AuditTrail GetNamesAddressesEmployers(long registryId, int changedField, AuditField defaultValue) { var otherNameAndAddress = (from a in context.AuditTrails where a.ChangedField == changedField && a.RegistryId == registryId select a).FirstOrDefault(); return otherNameAndAddress && defaultValue; } 

or save it as it is at present, and use it on the call site:

 var auditTrail = GetNamesAddressesEmployers(registryId, changedField) ?? new AuditTrail { Name = "Foo", Description = "Bar" }; 

It’s not entirely clear what is best based on your description.

EDIT: As Justin already mentioned, you can use DefaultIfEmpty (before FirstOrDefault ). This means that you need to pass the value, and not do it on the call site, but other than that they are very similar.

+1
source

All Articles