无法将类型的对象强制转换为类型'System.Data.Objects.ObjectContext

时间:2013-08-08 08:19:03

标签: entity-framework-4

我一直在关注本教程 - > http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-2

我陷入了主题 - 修改EntityDataSource控制标记以提高性能。当我通过删除ContextTypeNameConnectionString设置DefaultContainerName属性时,我收到错误消息;

Unable to cast object of type 'ContosoUniversity.DAL.SchoolEntities' to type 'System.Data.Objects.ObjectContext'.

请注意:使用ConnectionStringDefaultContainerName可以正常使用。

2 个答案:

答案 0 :(得分:1)

尝试以下MSDN文章的链接解决了我在浏览相同教程时遇到的问题。

MSDN Article

只需在方法SchoolContextEntityDataSource_ContextCreating()

中将SchoolContext更改为SchoolEntities

代码就像这样:

protected void SchoolContextEntityDataSource_ContextCreating(object sender,    EntityDataSourceContextCreatingEventArgs e)
{
   var db = new SchoolContext();
   e.Context = (db as IObjectContextAdapter).ObjectContext;
}

并添加

using System.Data.Entity.Infrastructure;

致以最诚挚的问候,

Adit Malik

答案 1 :(得分:0)

首先使用EntityDataSource structral aspx代码中的OnContextCreating方法 然后实现OnContextCreating方法:

    protected void StudentsEntityDataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
    {
        var db = new ContosoUniversity.DAL.schoolEntities();
        e.Context = (db as IObjectContextAdapter).ObjectContext;
    }

并添加: 使用System.Data.Entity.Infrastructure;