ORMLite SqlList<Tuple>查询异常:仅首个元组对象属性被赋值
解决ORMLite映射Tuple多元素失败的问题
我之前也碰到过一模一样的问题,ORMLite对Tuple<T1,T2,T3>这类复合类型的自动映射支持并不理想——它没法智能地把查询返回的多表字段分别分配到Tuple的Item1、Item2、Item3对应的实体属性里,只会一股脑把所有字段往第一个实体(也就是Definition)里塞,剩下的两个自然就保持默认状态了。
下面给你几个实用的解决方案:
方案1:使用自定义DTO类(推荐)
创建一个专门的数据传输对象,把三个实体作为它的属性,ORMLite能完美识别这种结构并完成映射:
// 自定义DTO类,清晰对应查询返回的三个表数据 public class DefinitionTimeslotTypeDto { public Definition Definition { get; set; } public Timeslot Timeslot { get; set; } public Type Type { get; set; } } // 修改查询代码 var query = "select definition.*, timeslot.*, type.* from <blah blah>"; var dtoList = dbConnection.SqlList<DefinitionTimeslotTypeDto>(query, new { /* query parameters */ }); // 如果确实需要Tuple格式,后续可以轻松转换 var tupleList = dtoList.Select(d => Tuple.Create(d.Definition, d.Timeslot, d.Type)).ToList();
方案2:手动映射动态结果
如果不想额外创建DTO类,可以先把查询结果转为dynamic类型,再手动组装Tuple:
var query = "select definition.*, timeslot.*, type.* from <blah blah>"; var dynamicResults = dbConnection.SqlList<dynamic>(query, new { /* query parameters */ }); var tupleList = new List<Tuple<Definition, Timeslot, Type>>(); foreach (var result in dynamicResults) { // 手动将动态对象的属性赋值给各个实体(替换成你的实际字段名) var definition = new Definition { Id = result.Id, Title = result.Title, // 其他Definition属性... }; var timeslot = new Timeslot { SlotId = result.SlotId, StartTime = result.StartTime, // 其他Timeslot属性... }; var type = new Type { TypeId = result.TypeId, Category = result.Category, // 其他Type属性... }; tupleList.Add(Tuple.Create(definition, timeslot, type)); }
方案3:给字段加别名指定映射
你也可以在SQL查询里给每个字段加上特定格式的别名,让ORMLite能识别到Tuple的对应项,不过这种方式字段多的时候会很繁琐:
var query = @" select definition.Id as Item1_Id, definition.Title as Item1_Title, -- Definition的所有字段都加上Item1_前缀 timeslot.SlotId as Item2_SlotId, timeslot.StartTime as Item2_StartTime, -- Timeslot的所有字段都加上Item2_前缀 type.TypeId as Item3_TypeId, type.Category as Item3_Category -- Type的所有字段都加上Item3_前缀 from <blah blah>"; var defs = dbConnection.SqlList<Tuple<Definition, Timeslot, Type>>(query, new { /* query parameters */ });
这种方式要求别名严格遵循ItemX_PropertyName的格式,ORMLite才能正确把字段映射到对应Tuple项的属性上。
总的来说,方案1是最清晰、最易维护的,推荐优先使用。
内容的提问来源于stack exchange,提问作者magicleon94
相关产品推荐
相关产品推荐

