c# - 无法将类型为 'System.Web.UI.WebControls.EntityDataSourceWrapper' 的对象转换为类型

标签 c# asp.net casting

我使用 asp.net 和 c#。

我有一个 DetailsView,我需要获取绑定(bind)到它的数据。

我收到此错误:您知道如何解决吗? 感谢您的宝贵时间。

请提供代码示例。

// Get the data for underlying DetailsView
DetailsView myDetailsView = ((DetailsView)sender);
WebProject.DataAccess.DatabaseModels.CmsContent rowView (WebProject.DataAccess.DatabaseModels.CmsContent)myDetailsView.DataItem;

Unable to cast object of type 'System.Web.UI.WebControls.EntityDataSourceWrapper' to type 'WebProject.DataAccess.DatabaseModels.CmsContent'. 

最佳答案

要从 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;
    }
}

然后调用

var row = EntityDataSourceExtensions.GetItemObject<WebProject.DataAccess.DatabaseModels.CmsContent>(myDetailsView.DataItem)

关于c# - 无法将类型为 'System.Web.UI.WebControls.EntityDataSourceWrapper' 的对象转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6502774/

相关文章:

c# - 用卷纸打印收据

具有相同名称的 Controller 的 asp.net Web api 路由

C# 泛型和转换

c# - 获取字体支持的字符 - 在 C# 中

c# - JumpList.GetJumpList 不包含最近的项目

c# - MVC3 的好处?

c# - 以编程方式获取转换和输出运算符类型

仅通过类型转换就可以完成符号/零扩展吗?

c# - Metro Style 应用程序的颜色选择器?

c# - 在 ASP 中打开并读取 txt 文件