加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

entity-framework – DbContext未在ASP.Net MVC中使用SQL Server

发布时间:2020-12-15 20:39:25 所属栏目:asp.Net 来源:网络整理
导读:我在Visual Studion 2013 Express for Web中使用ASP.Net MVC模板创建了一个简单的项目.它不使用任何身份验证.然后我安装了EntityFramework(v6.0.1),EntityFramework.SqlServerCompact包. 我的DbContext类非常简单: public class EditTestContext : DbContex
我在Visual Studion 2013 Express for Web中使用ASP.Net MVC模板创建了一个简单的项目.它不使用任何身份验证.然后我安装了EntityFramework(v6.0.1),EntityFramework.SqlServerCompact包.

我的DbContext类非常简单:

public class EditTestContext : DbContext
{
    public EditTestContext() : base("EditTestContext")
    {
    }

    public EditTestContext(string connectionString) : base(connectionString)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(
                       new DropCreateDatabaseIfModelChanges<EditTestContext>());
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Configurations.Add(new EditTestConfig());
    }
}

实际的上下文对象是在Unit of Work类中创建的:

public class EditTestUoW:IEditTestUoW,IDisposable
{
    private DbContext dbContext;

    public EditTestUoW()
    {
        CreateDbContext();
    }

    private void CreateDbContext()
    {
        dbContext = new EditTestContext();//NEW DBCONTEXT OBJECT IS CREATED
        dbContext.Configuration.LazyLoadingEnabled = false;
        dbContext.Configuration.ProxyCreationEnabled = false;
        dbContext.Configuration.ValidateOnSaveEnabled = false;
    }

    public IRepository<EditTestModel> EditTestRepo
    {
        get 
        {
            return new EFRepository<EditTestModel>(dbContext);
        }
    }
}

使用的连接字符串是:

<add name="EditTestContext" connectionString="Data Source=
    |DataDirectory|EditTestDb.sdf;Max Database Size=256;
    Max Buffer Size=1024;File Mode=Shared Read;
    Persist Security Info=False;" providerName="System.Data.SqlServerCe.4.0" />

现在,当我尝试使用此上下文访问任何内容时:

var rep=UoW.EditTestRepo;
var list=rep.GetAll().ToList();

我在rep.GetAll()函数上遇到以下异常:

System.InvalidOperationException:Sequence不包含匹配元素

在深入挖掘时,Repository类(DbSet< EditTest>)中的IQueryable抛出以下异常:

The context cannot be used while the model is being created. This exception may
be thrown if the context is used inside the OnModelCreating method or if the same
context instance is accessed by multiple threads concurrently. Note that instance
members of DbContext and related classes are not guaranteed to be thread safe.

我认为它可能是由ninject造成的,但即使在我删除它之后它仍然存在.

我在这里做错了什么(某些装配参考等)丢失了?

解决方法

在经过一番其他搜索后,我得到了 this MSDN论坛链接.正如Rowan所建议的那样,我尝试使用EFRepository类中的以下语句手动初始化上下文:
dbContext.Database.Initialize(false);

应用程序在访问GetAll()方法之前失败了.但这暴露了堆栈跟踪,这给了我一些方向:

[InvalidOperationException: Sequence contains no matching element]
   System.Linq.Enumerable.Single(IEnumerable`1 source,Func`2 predicate) +2614017
   System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName
                        (DbProviderManifest providerManifest,String name) +146
   .....Other Lines.....
   System.Data.Entity.Internal.InternalContext.Initialize() +31
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType
                                                            (Type entityType) +38
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +138
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +38
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable
                      .get_Provider() +99
   System.Linq.Queryable.Any(IQueryable`1 source) +50

然后搜索DbProviderManifestExtensions.GetStoreTypeFromName显示这是EF试图获取列类型的行.我为我的Id列指定了UNIQUEIDENTIFIER:

Property(x=> x.Id).HasColumnType("UNIQUEIDENTIFIER")

一旦我对此发表评论,一切都很顺利.

虽然Codeplex上有一个request来提供正确的错误消息,以防列类型对数据库提供程序无效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读