How to return null from a Dapper query rather than default(T)?

 ̄綄美尐妖づ 提交于 2019-11-29 10:32:16

If your SP doesn't return a row, then dapper won't return a row; so first thing to check: did your SP perhaps return an empty row? A row of all nulls ? Or did it return 0 rows?

Now, assuming no row was returned, FirstOrDefault (the standard LINQ-to-Objects thing) will return null if CaseOfficer is a class, or a default instance if CaseOfficer is a struct. So next: check CaseOfficer is a class (I can't think of any sane reason that would be a struct).

But: dapper with FirstOrDefault will generally already do what you want.

You can set default properties.

For example:

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; }
}

Now, CaseOfficer got auto-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!