我使用的是小巧玲珑的用于通过存储过程的一些只读数据库调用。 我有一个查询,或者返回1行或没有。
我使用的是小巧玲珑的是这样的:
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Query<CaseOfficer>("API.GetCaseOfficer",
new { Reference = reference },
commandType: CommandType.StoredProcedure).FirstOrDefault();
}
返回CaseOfficer对象看起来是这样的:
public class CaseOfficer
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
这是然后通过的ASP.NET Web API应用程序作为JSON返回。
当存储过程返回一个结果我得到如下:
{
title: "Mr",
firstName: "Case",
lastName: "Officer",
email: "test@example.com",
telephone: "01234 567890"
}
但是,当它没有返回,我得到:
{
title: null,
firstName: null,
lastName: null,
email: null,
telephone: null
}
我怎样才能得到小巧玲珑返回NULL(这样我就可以检查,并与404回应),而不是默认的(CaseOfficer)?
如果SP不返回行,那么短小精悍不会返回一行; 所以首先要检查:你的SP可能返回一个空行? 所有的行null
S' 还是因为它返回0行?
现在,假设没有返回行, FirstOrDefault
(标准LINQ到对象的事情)将返回null
,如果CaseOfficer
是一个class
,或默认实例,如果CaseOfficer
是一个struct
。 因此,下:检查CaseOfficer
是一个class
(我想不出任何理由理智,这将是一个struct
)。
但是:短小精悍与FirstOrDefault
一般会已经做你想做的。
您可以设置默认属性。
例如:
public class BaseEntity
{
public BaseEntity()
{
if (GetType().IsSubclassOf(typeof(BaseEntity)))
{
var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
// Get only string properties
if (property.PropertyType != typeof (string))
{
continue;
}
if (!property.CanWrite || !property.CanRead)
{
continue;
}
if (property.GetGetMethod(false) == null)
{
continue;
}
if (property.GetSetMethod(false) == null)
{
continue;
}
if (string.IsNullOrEmpty((string) property.GetValue(this, null)))
{
property.SetValue(this, string.Empty, null);
}
}
}
}
}
public class CaseOfficer : BaseEntity
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
现在,CaseOfficer了自动性能