Can a Entity Framework Trackable collection be bound to an ASP.Net Gridview?

故事扮演 提交于 2019-12-11 23:55:56

问题


I've got a GridView on a ASP.Net page. I would like to set the DataSource of the Gridview to a trackable collection of Entity Framework objects. I though the code should look like this:

        this.gvMyGridView.DataSource = entity.MyDetailedItems;
        this.gvMyGridView.DataBind();

But this doesn't display any data.

I am using self tracking entities and the MyDetailedItems is a navigation property to rows from another table.


回答1:


EF 4 with self tracking entities does not support lazy loading so you must explicitly load navigation properties if you want to use them. Use either:

// loading entity with related entities
var entity = context.Entities.Include("MyDetailedItems").Single(...);

or

// loading related entities for already loaded entity
context.LoadProperty(entity, "MyDetailedItems");



回答2:


Yes, it can. If you are not using the lazy loading (LazyLoadingEnabled to true), then these relationships do not automatically load, and you have to do:

if (entity.MyDetailedItems.IsLoaded == false)
    entity.MyDetailedItems.Load();

Before binding, otherwise, if using EF 4 turn on lazy loading enabled, and this no longer becomes a problem.

HTH.



来源:https://stackoverflow.com/questions/5461487/can-a-entity-framework-trackable-collection-be-bound-to-an-asp-net-gridview

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