我的以下查询
var varUser = (from d in db.tblUsers where (d.ID == intID) select d).SingleOrDefault();
return varUser.Forename + " " + varUser.Surname;
使用 single 或 default 时如何输出默认值?所以名字和姓氏是空的,我想写“没有用户”
谢谢
检查用户是否是null
(默认情况)并返回一些默认值(或抛出异常)
if (varUser == null)
return "No User"; // default value or exception
return String.Format("{0} {1}", varUser.Forename, varUser.Surname);
提示:您可以将条件传递给SingleOrDefault方法:
db.tblUsers.SingleOrDefault(u => u.ID == intID)
如果您使用的是实体框架,甚至可以使用Find(如果在上下文跟踪的实体中找不到实体,它在内部调用 SingleOrDefault)
db.tblUsers.Find(intID)
return var varUser = db.tblUsers.SingleOrDefault(x=>x.id == intID) ?? "No User";
尝试这个
return varUser == null ? "No User" :
string.Concat(varUser.Forename, " " , varUser.Surname);
将只读属性添加到您的用户类:
Public Class User
Public Property FirstName As String
Public Property LastName As String
Public ReadOnly Property FullName() As String
Get
If String.IsNullOrEmpty(FirstName) AndAlso String.IsNullOrEmpty(LastName) Then
Return "No Name"
Else
Return FirstName & " " & LastName
End If
End Get
End Property
End Class
现在您可以像这样使用您的 LINQ 语句(DefaultIfEmpty子句):
Dim varUser = (From d In db.tblUsers Where (d.ID == intID) Select d).DefaultIfEmpty(New User).SingleOrDefault()
Return varUser.FullName
抱歉,我不精通 C#,因此是 VB 代码。但你明白了。