How to return Wrapper obj of TableOjb1 and TableObj2 using linq

只谈情不闲聊 提交于 2019-12-08 17:28:17

问题


class TableObj1 {
    public string Id {get; set;}
    public string Name {get; set;}
}

class TableObj2 {
    public string Id {get; set;}
    public string Email {get; set;}
}

class MergeObj {
    public TableObj1 Obj1 {get; set;}
    public TableObj2 Obj2 {get; set;}
}

My question is how to return a list of MergeObj when joining the two tables. I tried:

public IEnumerable<MergeObj> QueryJoin() {
    return (
        from obj1 in conn.Table<TableObj1>()
        join obj2 in conn.Table<TableObj2>()
        on obj1.Id
        equals obj2.Id
        select new MergeObj{Obj1 = obj1, Obj2 = obj2}
    );
}

void main() {
    IEnumerable<MergeObj> mergeObjs = QueryJoin();
}

But QueryJoin() gives Exception: System.NotSupportedException, Joins are not supported.

please note I'm using sqlite.net not ADO.net.


回答1:


Try doing the select after casting the join result to a list.

public IEnumerable<MergeObj> QueryJoin()
    {
        List<TableObj1> t1 = conn.Table<TableObj1>().ToList();
        List<TableObj2> t2 = conn.Table<TableObj2>().ToList();

        return t1.Join(t2, outer => outer.Id, 
                           inner => inner.Id, 
                           (outer, inner) => new MergeObj { Obj1 = outer, Obj2 = inner });
    }

Edit : Since your database don't seems to support join, you can extract the result of your database in two distinct List and then join them using LINQ.




回答2:


You might need to project to an anonymous type, then create your objects using Linq-to-Objects:

public IEnumerable<MergeObj> QueryJoin() {
    return (
        from obj1 in conn.Table<TableObj1>()
        join obj2 in conn.Table<TableObj2>()
        on obj1.Id
        equals obj2.Id
        select new {obj1, obj2}
    ).AsEnumerable()
     .Select(o => new MergeObj{Obj1 = o.obj1, Obj2 = o.obj2}) ;
}


来源:https://stackoverflow.com/questions/26410146/how-to-return-wrapper-obj-of-tableojb1-and-tableobj2-using-linq

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