C# 如何 return null 或模型
C# How to return null or an model
我有商店模型,如果我的模型为空,我想 return 为空。
public Store Details() => db.Store.Single(s => s.Id == 1);
此查询有时 return 一个值,有时 return 为空值。我如何指定 return 类型以包含两者?
尝试使用
public Store Details() => db.Store.FirstOrDefault(s => s.Id == 1);
使用 SingleOrDefault 而不是 FirstOrDefault,因为如果找到多个则抛出异常
// throws an exception if there's more than one entity that fits the filter part.
public Store Details() => db.Store.SingleOrDefault(s => s.Id == 1);
// doesn't throw if there's more than one entity that fits the filter part
public Store Details() => db.Store.FirstOrDefault(s => s.Id == 1);
我有商店模型,如果我的模型为空,我想 return 为空。
public Store Details() => db.Store.Single(s => s.Id == 1);
此查询有时 return 一个值,有时 return 为空值。我如何指定 return 类型以包含两者?
尝试使用
public Store Details() => db.Store.FirstOrDefault(s => s.Id == 1);
使用 SingleOrDefault 而不是 FirstOrDefault,因为如果找到多个则抛出异常
// throws an exception if there's more than one entity that fits the filter part.
public Store Details() => db.Store.SingleOrDefault(s => s.Id == 1);
// doesn't throw if there's more than one entity that fits the filter part
public Store Details() => db.Store.FirstOrDefault(s => s.Id == 1);