ORMLite是否支持C#的动态类型?

时间:2014-12-18 02:05:47

标签: c# orm servicestack ormlite-servicestack

我正在调查来自ServiceStack的ORMLite,我在这里尝试的是调用一个存储过程,该存储过程又返回许多行,这些行肯定不会绑定到任何域对象,但也可能有或没有dto用于映射的对象。我想知道我是否可以将它绑定到一个类型。但是,听起来ORMLite目前不支持动态类型绑定。此时ORMLite是否支持?

1 个答案:

答案 0 :(得分:5)

按设计OrmLite不支持对动态类型进行编组,并期望将结果集映射到Typed POCO。

虽然它确实有专门的API来使用C#7元组访问Dynamic Result Sets

var query = db.From<Employee>()
    .Join<Department>()
    .OrderBy(e => e.Id)
    .Select<Employee, Department>(
        (e, d) => new { e.Id, e.LastName, d.Name });

var results = db.Select<(int id, string lastName, string deptName)>(query);

var row = results[i];
$"row: ${row.id}, ${row.lastName}, ${row.deptName}".Print();

List<object>

db.Select<List<object>>(db.From<Poco>()
  .Select("COUNT(*), MIN(Id), MAX(Id)"))[0].PrintDump();

/* Output */
[
    10,
    1,
    10
]

或使用Dictionary<string,object>,例如:

db.Select<Dictionary<string,object>>(db.From<Poco>()
  .Select("COUNT(*) Total, MIN(Id) MinId, MAX(Id) MaxId"))[0].PrintDump();

/* Output */
{
    Total: 10,
    MinId: 1,
    MaxId: 10
}

除了能够映射到松散类型的.NET集合之外:

Dictionary<int, string> trackIdNamesMap = db.Dictionary<int, string>(
    "select Id, Name from Track")

Dictionary<int, List<string>> albumTrackNames = db.Lookup<int, string>(
    "select AlbumId, Name from Track")

List<string> trackNames = db.Column<string>("select Name from Track")

HashSet<string> uniqueTrackNames = db.ColumnDistinct<string>("select Name from Track")

使用Dapper的查询

OrmLite的Dapper嵌入版本为does support dynamic results

using ServiceStack.OrmLite.Dapper;

using (var db = new SqlConnection(@"Data Source=... etc."))
{
    db.Open();

    var p = new DynamicParameters();
    p.Add("@params", "Id=21");

    IEnumerable<dynamic> dynamicResults = db.Query(sql:"GetPivotData", param: p,
        commandType:CommandType.StoredProcedure);
}