使用Dapper混合复杂对象

时间:2018-08-27 17:42:26

标签: c# dapper

我对此做了一些深入研究,但是我不太理解。我在对象上有一个Microsoft.Extensions.Logging.EventId,并且我已经使用Dapper在数据库中保留了EventId。我使用了两列:EventId(int)和EventName(varchar(…))。但是,我不太清楚如何从两个数据库列中填充一个属性对象(EventId)。

我试图操纵我的SQL。

SELECT <snip>…[EventId] AS [EventId.Id],[EventName] AS [EventId.Name] . . .

,但效果如您所料。

所以,这是我的xunit测试:

[Fact]
public async Task EventName_Retrievable()
{
    logger.Log(logLevel: LogLevel.Critical,
        eventId: new EventId(10, "find me"),
        exception: null,
        state: "yes please",
        formatter: (s, e) =>
        {
            return e?.Message ?? s;
        });

    var criteria = new LogQueryCriteria
    {
        MessageContains = "yes please"
    };
    var service = new LogQueryService(_fixture.ConnectionString, _factory, _performanceAgent);

    var logs = await service.FindLogsAsync(criteria);

    Assert.NotEmpty(logs);

    Assert.Equal("find me", logs.Last().EventId.Name);
}

证明此功能不起作用:

    public async Task<IEnumerable<ILogItemOutbound>> FindLogsAsync(LogQueryCriteria criteria)
    {
        var pe = _performanceAgent?.Start($"{nameof(LogQueryService)}.{nameof(FindLogsAsync)}", PerformanceTrackingLevel.Low);

        if (criteria == null) { criteria = new LogQueryCriteria(); }

        IEnumerable<ILogItemOutbound> results = null;
        var sql = $@"
{Constants.SELECT_LOGS}{ConstructWhereClause(criteria)} {ConstructOrderByClause(criteria)}
OFFSET {criteria.OffsetValue} ROWS FETCH NEXT {criteria.NumberPerPage} ROWS ONLY;";

        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            results = await connection.QueryAsync<LogItemOutbound, EventId, LogItemOutbound>(sql: sql, commandType: System.Data.CommandType.Text,
                map: (logItem, eventId) =>
                {
                    logItem.EventId = eventId;
                    return logItem;
                }
            , splitOn: "EventId");
            _performanceAgent?.Finish(pe);
        }

        return results ?? new List<ILogItemOutbound>();
    }

您可以看到我试图像这个人一样使用map函数:https://taylorhutchison.github.io/2016/03/23/dapper-orm-complex-queries.html,但是不管我采用哪种方法,Name总是变成NULL。

有人看到我要去哪里了吗?

如果相关,这是我的SQL:

    internal const string SELECT_LOGS = @"
SET NOCOUNT ON;
SET DEADLOCK_PRIORITY NORMAL;

SELECT [GlobalId]
,[UtcTimestamp]
,[Message]
,[LogLevel]
,[LogLevelName]
,[Source]
,[UserIdentity]
,[SessionId]
,[EventId]
,[EventName]
FROM [dbo].[Logs]";

总是很乐意提供帮助。

V

1 个答案:

答案 0 :(得分:1)

EventName将不会映射到Event.Name

将您的SQL更改为

 internal const string SELECT_LOGS = @"
SET NOCOUNT ON;
SET DEADLOCK_PRIORITY NORMAL;

SELECT [GlobalId]
,[UtcTimestamp]
,[Message]
,[LogLevel]
,[LogLevelName]
,[Source]
,[UserIdentity]
,[SessionId]
,[EventId] as Id
,[EventName] as Name
FROM [dbo].[Logs]";

和您的spliton: "Id"