无法将类型为"System.Web.UI.WebControls.EntityDataSourceWrapper"的对象强制转换为类型

Gib*_*boK 2 c# asp.net casting

我使用asp.net和c#.

我有一个DetailsView,我需要获取绑定到它的数据.

我收到此错误:您是否知道如何解决此问题?谢谢你的时间.

请提供一些代码示例.

// Get the data for underlying DetailsView
DetailsView myDetailsView = ((DetailsView)sender);
WebProject.DataAccess.DatabaseModels.CmsContent rowView (WebProject.DataAccess.DatabaseModels.CmsContent)myDetailsView.DataItem;
Run Code Online (Sandbox Code Playgroud)
Unable to cast object of type 'System.Web.UI.WebControls.EntityDataSourceWrapper' to type 'WebProject.DataAccess.DatabaseModels.CmsContent'. 
Run Code Online (Sandbox Code Playgroud)

Sta*_*kov 5

要从DataItem获取对象,您需要使用此处描述的方法:http://blogs.msdn.com/b/diego/archive/2008/05/13/entitydatasource-to-wrap-or-not-to-wrap.aspx 即创建类

static class EntityDataSourceExtensions
{
    public static TEntity GetItemObject<TEntity>(object dataItem) where TEntity : class
    {
        var entity = dataItem as TEntity;
        if (entity != null)
        {
            return entity;
        }
        var td = dataItem as ICustomTypeDescriptor;
        if (td != null)
        {
            return (TEntity)td.GetPropertyOwner(null);
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

var row = EntityDataSourceExtensions.GetItemObject<WebProject.DataAccess.DatabaseModels.CmsContent>(myDetailsView.DataItem)
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.很高兴看到它很容易打开对象 - 不是! (2认同)