How to Return Extra Data with IQueryable method?

我怕爱的太早我们不能终老 提交于 2019-12-06 12:01:13

Take a look at the EntityQuery.withParameters method.

// client side
var q = EntityQuery.from("CustomersStartingWith")
        .withParameters({ companyName: "C" });


// server side
[HttpGet]
public IQueryable<Customer> CustomersStartingWith(string companyName) {
  var custs = ContextProvider.Context.Customers.Where(c => c.CompanyName.StartsWith(companyName));
  return custs;
}

You can also mix and match a combination of regular query predicates with these custom parameters.

nlips

LINQ to entity can only construct pur "Data Transfert Object" : class containing only public properties with trivial getter and setter and without constructor. See my answer to a similar question here : https://stackoverflow.com/a/21174654/3187237

I specify my answer

An Entity class can't be instanciated in a LINQ to Entities query. If you want to construct similar (or almost similar) in the query you have to define an other class.

In your case you want to return object almost similar to your MyObject. So you have to define a class:

public class MyObjectExtended
{
    public string FieldA { get; set; }
    public string FieldB { get; set; }
    // ... all other MyObjetc fields
    public string ExtraFieldA { get; set; }
    public string ExtraFieldB { get; set; }
}

Now, your service can return a IQueryable<MyObjectExtended>:

public IQueryable<MyObjectExtended> MyObjectsWithExtraData() {
    var myQuery = from o in _contextProvider.Context.MyObjects
        // big complex query....
        select new MyObjectExtended {
           FieldA = o.FieldA,
           FieldB = o.FieldB,
           //... all fields ...
           ExtraFieldA = x.ResultFromComplexJoinA,
           ExtraFieldB = x.ResultFromComplexJoinB
    };
    return myQuery;
}

I hope this is what you are looking for.

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