如何从EntitydataSource绑定gridview中的RowDataBound获取实体对象

时间:2010-01-13 00:12:54

标签: entity-framework gridview

我有一个绑定到Entity Framework对象的GridView。我想访问GridView的RowDataBound事件中的对象。当我尝试访问DataItem对象时,我收到一条错误,指出无法将“System.Data.Objects.MaterializedDataRecord”类型的对象强制转换为“BBM.NailArtGallery.Model.Item”。显然,MaterializedDataRecord是一些隐藏属性。有谁知道怎么解决这个问题。我的GridView使用和EntityDataSource Control绑定。代码如下。

<asp:EntityDataSource ID="EntityDataSource1" runat="server" AutoPage="true" AutoSort="true" OrderBy="it.ID"
    ConnectionString="name=Entities" DefaultContainerName="Entities" 
    EntitySetName="Items" EntityTypeFilter="ItemImage"  
    Select="it.[ID], it.[Title], it.[IsFeatured], it.[ImageHome], it.[DateEntered]">
</asp:EntityDataSource>

if (e.Row.RowType == DataControlRowType.DataRow)
        {          
            ICustomTypeDescriptor descriptor = (ICustomTypeDescriptor)e.Row.DataItem;
            if (descriptor != null)
            {
                var prop = (PropertyDescriptor)descriptor.GetProperties()[0];
                Item image = (Item)descriptor.GetPropertyOwner(prop);

            }

        }

2 个答案:

答案 0 :(得分:1)

根据Reflector,MaterializedDataRecord是一个继承DbDataRecord的内部类,因此您可以使用GetInt32GetStringGetDateTime等访问其属性方法,或通过索引器

答案 1 :(得分:0)

RowDataBound代码可能如下所示:

If e.Row.RowType = DataControlRowType.DataRow Then 

    Dim rowItem = CType(e.Row.DataItem, Data.Common.DbDataRecord) 

    Dim myItemID As Integer = rowItem("ID") 
    Dim myTitle As String = rowItem("Title")

End If