我有Store Model,如果我的模型为null,我想返回null。
public Store Details() => db.Store.Single(s => s.Id == 1);
此查询有时会返回一个值,有时会返回null。如何指定返回类型以包含两者?
答案 0 :(得分:6)
尝试使用
public Store Details() => db.Store.FirstOrDefault(s => s.Id == 1);
答案 1 :(得分:2)
使用 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);