Does ORMLite support dynamic Type of C#?

主宰稳场 提交于 2019-12-06 09:17:48

问题


I am looking into ORMLite from ServiceStack and what I am trying to do here is that call a stored procedure which in turn return many many rows which definitely would not be bound to any domain object but also may or may not have a dto object to map with. I was wondering if I can bind it to a type. However, it sounds like ORMLite does not support dynamic type binding at this time. Does ORMLite support at this point?


回答1:


By design OrmLite does not support marshalling to dynamic types, and expects resultsets to mapped to Typed POCO's.

Although it does have specialized API's to access Dynamic Result Sets using C# 7 Tuples:

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();

Or List<object>:

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

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

Or using Dictionary<string,object>, e.g:

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
}

As well as being able to map into loose-typed .NET collections:

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")

Using Dapper's Query

OrmLite does have an embedded version of Dapper which 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);
}


来源:https://stackoverflow.com/questions/27538114/does-ormlite-support-dynamic-type-of-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!