I have a GridView that is bound to an Entity Fram开发者_如何转开发ework object. I want to access the object in the RowDataBound event of the GridView. When I try to access the DataItem object i get an error stating Unable to cast object of type 'System.Data.Objects.MaterializedDataRecord' to type 'BBM.NailArtGallery.Model.Item'. Apparently the MaterializedDataRecord is some hidden property. Does anyone know how to get around this. My GridView is bound using and EntityDataSource Control. The code is below.
<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);
}
}
According to Reflector, MaterializedDataRecord
is a internal class that inherits DbDataRecord
, so you can access its properties with the GetInt32
, GetString
, GetDateTime
etc methods, or through the indexer
The RowDataBound code might look something like this:
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
精彩评论