LINQ 查询中的默认值
我的 MVC3 应用程序中有以下 Linq 查询/函数。
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;
}
我希望如果 otherNameAndAddress = null 则应为其属性分配一些值。
otherNameAndAddress 具有名称和描述属性。此 GetNamesAddressesEmployers 已在 3 个地方使用。当所有三个位置的 otherNameAndAddress = null 时,我想为名称和描述分配不同的值。
I have following Linq query/function in my 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 that if otherNameAndAddress = null then its properties should be assigned some values.
otherNameAndAddress has Name and description property. This GetNamesAddressesEmployers is being used at 3 places. I want to assign different values to name and description when otherNameAndAddress = null at all three locations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经在使用 FirstOrDefault() 那么为什么不指定默认值:
You're already using FirstOrDefault() so why not specify the Default:
好吧,您可以将 return 语句更改为:
或类似的内容...但是您说您想为不同的调用分配不同的默认值。这意味着您要么需要传入默认值,要么在调用站点执行默认设置(例如,以相同的方式,通过空合并运算符)。
例如:
或保持当前状态,并在调用站点使用它:
根据您的描述,尚不清楚哪个最好。
编辑:正如贾斯汀提到的,您可以使用
DefaultIfEmpty
< /a> 代替(就在FirstOrDefault
之前)。这意味着您必须传入值,而不是在调用站点执行此操作,但除此之外,它们是非常相似的解决方案。Well, you could change the return statement to:
or something like that... but you say you want to assign different default values for different calls. That means you'll either need to pass the default in, or perform the defaulting (e.g. in the same way, via the null-coalescing operator) at the call site.
For example:
or keep it as it currently is, and use this at the call site:
It's not really clear which is best based on your description.
EDIT: As mentioned by Justin, you could use
DefaultIfEmpty
instead (just beforeFirstOrDefault
). That means you have to pass the value in rather than doing it at the call site, but other than that they're very similar solutions.