开发者

Databind ListView datasource and joined tables

I am not expert in ASP so i would be appreciated for the help. Issue connected to Entity FW, ListView Control, its Datasource and type convertion.

I have the following LINQ query :

RoutesEntities routesModel = new RoutesEntities();
LocalesEntities localesModel = new LocalesEntities();
ObjectQuery routesQuery = (ObjectQuery) from routes in routesModel.Routes
                                        join locales in localesModel.Locales
                                        on routes.LocaleID equals locales.LocaleID
                                        where locales.IsActive == true
                                        select new {
                                             LocaleID = routes.LocaleID,
                                             RouteName = routes.RouteName
                                        };

AdminTopListView.DataSource = routesQuery;
AdminTopListView.DataBind(); // this line cause the error

If there is no JOIN for tables all is OK. In all other cases i get the error says that there are 2 contexts for only one LI开发者_JAVA百科NQ statement.

The questions are :

  1. what types except ObjectQuery can be accepted by ListView datasource?
  2. how to convert Anonymous Type returned by LINQ to ObjectQuery?

Thanks in advance.


It happens to be the case that the error you observed is due not to data-binding, but to LINQ. LINQ queries are lazily executed, meaning they do not actually retrieve data until absolutely necessary. This explains why you do not see symptoms until the .DataBind() call.

A data binding statement to a list view can take many different kinds of data types. I usually bind an IList, array, or DataTable. Your LINQ query results will always apply if enumerable.

If you combine your data contexts into one context, you can perform your join without error. If that option is not available, retrieve your collections first as a local list, and then create a LINQ-to-objects query.

var routesQuery = from routes in routesModel.Routes.ToList()
                  join locales in localesModel.Locales.ToList()
                  on routes.LocaleID equals locales.LocaleID
                  // ...

(Note: you can achieve better performance if you pre-filter the result set prior to loading the data .ToList()).

I strongly prefer the solution of combining data contexts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜