I have the following enum
:
public enum EventType
{
LoginSuccessfully = 1,
LoginFailure = 2,
UserCreated = 3,
UnableToCreateUser = 4,
PasswordReseted = 5,
UnableToResetPassword = 6,
UserDeleted = 7,
UnableToDeleteUser = 8
}
And I have this method:
public IActionResult GetFilteredLogs([FromBody] SearchFilterContract contract)
{
//filter logs from database
}
Here is the contract
received as parameter
from my method:
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;}
}
If all the values from the contract
are Null
it gets All the values from database.
On my method I compare the variables of the contract
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);
The Int? EventId is the number received from the enum
Here's my controller method:
[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);
}
}
And here's my DataRepository method
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;
}
The exception is throwed when it calls on the Repository method the SearchStatementSource
method
My problem here is that when I put EventTypes
as Null it returns the following error:
"Nullable object must have a value"
Any ideas on how to fix this?