asp.net核心Enum Nullable对象必须有一个值

时间:2018-04-17 16:56:41

标签: c# asp.net-core enums nullable

我有以下enum

public enum EventType
        {
            LoginSuccessfully = 1,
            LoginFailure = 2,
            UserCreated = 3,
            UnableToCreateUser = 4,
            PasswordReseted = 5,
            UnableToResetPassword = 6,
            UserDeleted = 7,
            UnableToDeleteUser = 8
        }

我有这个方法:

public IActionResult GetFilteredLogs([FromBody] SearchFilterContract contract)
{
    //filter logs from database
}

以下是我的方法收到的contract parameter

 public class SearchFilterContract
    {
        public EventType? EventTypes { get; set; }
        public string Username { get; set; }
        public DateTime? fromDate { get; set; }
        public DateTime? toDate { get; set; }
        public int pageSize { get; set; }
        public int pageNumber {get; set;}

    }

如果contract中的所有值均为Null,则会从数据库中获取所有值。

在我的方法中,我比较了合同的变量

public SearchStatementSource(int? EventId,string username,DateTime? fromDate,DateTime? toDate,int pageSize, int PageNumber)

{
            StringBuilder sb = new StringBuilder();
 sb.AppendLine("SELECT * FROM [dbo].[eventslog] ");

            if(username != null)
            {
                sb.AppendLine("WHERE Username = @Username ");
            }
            else 
            {
                sb.AppendLine("WHERE Username IS NOT NULL ");
            }

            if(fromDate.HasValue)
            {
                sb.AppendLine("AND CreatedTime >= @fromDate ");
            }
            if(toDate.HasValue)
            {
                sb.AppendLine("AND CreatedTime <= @toDate ");
            }
            if(EventId.HasValue)
            {
                sb.AppendLine("AND EventId = @EventId ");
            }
            sb.AppendLine("AND Id >=" + startingIndex);
            sb.AppendLine("AND Id <=" + finalIndex);

            _command = sb.ToString();
Parameters.Add(new SqlParameter("@null","null"));
            AddNullable("@Username", username);
            AddNullable("@EventId", EventId);
            AddNullable("@fromDate", fromDate);
            AddNullable("@toDate",toDate);

国际? EventId是从枚举

收到的号码

这是我的控制器方法:

[HttpPost]
        [Route("[action]")]
        [AllowAnonymous]
        public IActionResult GetFilteredLogs([FromBody] SearchFilterContract contract)
        {
            try
            {
                List<EventsLog> eventsLog = _logsBl.SearchLogs(contract.EventTypes,contract.Username,contract.fromDate,contract.toDate,contract.pageNumber,contract.pageSize);
                return Ok(eventsLog);
            }
            catch(Exception ex)
            {
                return BadRequest(ex);
            }
        }

这是我的DataRepository方法

public List<EventsLog> SearchLogs(EventType? EventId, string username, DateTime? fromDate, DateTime? toDate,int pageSize, int pageNumber)
        {
            List<EventsLog> logs = new List<EventsLog>();
            DataTable dt = Select(new SearchStatementSource((int)EventId,username,fromDate,toDate,pageSize,pageNumber));
            foreach(DataRow dr in dt.Rows)
            {
                logs.Add(Map(dr));
            }
            return logs;
        }

当它使用SearchStatementSource方法

调用Repository方法时抛出异常

我的问题是,当我将EventTypes设为Null时,它会返回以下错误:

&#34; Nullable对象必须具有值&#34;

有关如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:1)

您必须检查所有您使用的地点EventTypes.Value

那是因为您正在访问空对象的Value属性

See here on an Fiddle

你首先检查它:

if(obj.EventTypes.HasValue)
   //Do your logic

或者,如果您使用的是C#6,则可以使用此

obj.EventTypes ?? DefaultValue

<强>更新

你的问题在这里:

DataTable dt = Select(new SearchStatementSource((int)EventId, username, [...]

如果EventId为空,则将int投射到(int?)EventId

将其更改为DataTable dt = Select(new SearchStatementSource((int?)EventId, username, [...]

{{1}}