我有以下代码通过存储过程查询数据库。当ReturnObject.familymembers = multi.Read<InternalObjects.Person>().AsQueryable();
不为空时,返回正常;但是我找不到通过Dapper / linq处理带有集合类型的null返回的方法。
我的存储过程:
SELECT states.name as stateName, fam.*
FROM Family fam
WHERE fam.idUserName=@username
SELECT person.*
FROM person
INNER JOIN Family fam on fam.Id = person.idFamily
WHERE fam.idUserName=@username
当第二个SQL语句有记录时,设置ReturnObject.familymembers
没有任何问题,但是我无法确定如何指定默认值或从Dapper处理null返回。调试时,如果没有返回任何行,ReturnObject.familymembers = multi.Read<InternalObjects.Person>().AsQueryable()
将抛出一个空异常。
这是我认为可行的,但不是:
ReturnObject.familymembers = multi.Read<InternalObjects.Person>().AsQueryable().DefaultIfEmpty<InternalObjects.Person>();
public InternalObjects.FamilyDashboard GetDashboardInfo(string username)
{
InternalObjects.FamilyDashboard ReturnObject = new InternalObjects.FamilyDashboard();
using (var dbConnection = _dbConnectionFactory.CreateConnection())
{
using (var multi = dbConnection.QueryMultiple("DashboardSP", new { username = username }, commandType: CommandType.StoredProcedure))
{
ReturnObject = multi.Read<InternalObjects.FamilyDashboard>().SingleOrDefault();
ReturnObject.familymembers = multi.Read<InternalObjects.Person>().AsQueryable();
}
}
return ReturnObject;
}
我的DTO:
public class InternalObjects
{
public class FamilyDashboard
{
public string physicalAddress1 { get; set; }
public string MailingAddress1 { get; set; }
public string physicalAddressCity { get; set; }
public string physicalAddressZip { get; set; }
public string MailingAddressCity { get; set; }
public string NumInHousehold { get; set; }
public string capidCounty { get; set; }
public string physicalUnit { get; set; }
public string mailingUnit { get; set; }
public string familyPhone { get; set; }
public string capCharacteristics { get; set; }
public IEnumerable<Person> familymembers {get; set;}
}
public class Person
{
public int Id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string middleName { get; set; }
public int gender { get; set; }
public DateTime birthdate { get; set; }
public string emailPersonal { get; set; }
public string SSN { get; set; }
public string relationshipName { get; set; }
public string primaryLanguageName { get; set; }
public int age { get; set; }
}
}
答案 0 :(得分:0)
我找到了答案:
基本上,如果没有返回任何行,那么dapper不会返回任何值,而这些行不会实例化我的对象。我的父对象ReturnObject
没有被实例化,但仍然正常运行。
下一行ReturnObject.familymembers = multi.Read<InternalObjects.Person>().AsQueryable()
尝试访问该对象,但DTO不存在。
一个简单的条件节省了一天:
if (ReturnObject != null)
{
ReturnObject.familymembers = multi.Read<InternalObjects.Person>().ToList<InternalObjects.Person>();
}
参与其他任何人的参考!:
How to return null from a Dapper query rather than default(T)?
Getting Dapper to return an empty string instead of a null string