C#如何返回null或模型

时间:2017-08-28 18:04:27

标签: c# asp.net asp.net-mvc poco c#-7.0

我有Store Model,如果我的模型为null,我想返回null。

public Store Details() => db.Store.Single(s => s.Id == 1);

此查询有时会返回一个值,有时会返回null。如何指定返回类型以包含两者?

2 个答案:

答案 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);