初始化实体框架数据库序列时出错不包含匹配元素

时间:2015-01-23 14:49:49

标签: c# linq entity-framework ef-code-first

过去5个小时我一直在盯着这个,尝试了很多东西,但我没有得到任何地方......

当我尝试启动我使用Entity Framework Code First创建的数据库的MVC网站时,数据库无法初始化,抛出以下异常消息:

  

序列不包含匹配元素

下面的堆栈跟踪的第一行执行Linq .Single查询,所以我的印象是它在我的模型中寻找一个不存在的单个项目。如果这是正确的,我该如何找出该项目是什么?

此外,在抛出异常后,我已经达到我的智慧结束并因此决定通过绝对所有调试信息,我在我的Autos窗口中注意到以下内容:

Error message from Autos window

这直接引用了我的OnModelCreating覆盖:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new CompanyDBConfiguration());
        modelBuilder.Configurations.Add(new ClientDBConfiguration());
        modelBuilder.Configurations.Add(new QuoteDBConfiguration());
        modelBuilder.Configurations.Add(new RoleDBConfiguration());
        modelBuilder.Configurations.Add(new UserDBConfiguration());
        modelBuilder.Configurations.Add(new InvoiceDBConfiguration());
        modelBuilder.Configurations.Add(new JobDBConfiguration());
        modelBuilder.Configurations.Add(new JobStatusDBConfiguration());            
    }

非常感谢任何可用于让我更接近解决方案的信息。

如果这里没有足够的信息,我很抱歉,我不知道该提供什么。这是堆栈跟踪:(向下滚动以进行编辑)

  

System.InvalidOperationException未被用户代码
处理     的HResult = -2146233079
    消息=序列不包含匹配元素
    来源= System.Core程序
    堆栈跟踪:
         在System.Linq.Enumerable.Single [TSource](IEnumerable 1 source, Func 2谓词)
         at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest,String name)
         at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column,EntityType table,DbProviderManifest providerManifest,Boolean allowOverride,Boolean fillFromExistingConfiguration)
         at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration。<> c__DisplayClass1.b__0(Tuple 2 pm) at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable 1 ts,Action 1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable
1 propertyMappings,DbProviderManifest providerManifest,Boolean allowOverride,Boolean fillFromExistingConfiguration)
         at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList 1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy
2.GetValue(TInput input)
         在System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
         在System.Data.Entity.Internal.LazyInternalContext.MarkDatabaseInitialized()
         在System.Data.Entity.Database.Initialize(布尔力)
         位于e:\ Development \ Jobber \ Jobber.Web \ Global.asax.cs中的Jobber.Web.MvcApplication.Application_Start():第28行     InnerException:

编辑1

这是Global.asax的代码

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        WebDBContext db = new WebDBContext();
        db.Database.Initialize(true);
        db.Seed();
    }
}

这里是WebDBContext()

// BaseDBContext is a generic class that inherits from DbContext, see it's code below
public class WebDBContext : BaseDBContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new CompanyDBContext());
        modelBuilder.Configurations.Add(new ClientDBContext());
        modelBuilder.Configurations.Add(new QuoteDBContext());
        modelBuilder.Configurations.Add(new RoleDBContext());
        modelBuilder.Configurations.Add(new UserDBContext());
        modelBuilder.Configurations.Add(new InvoiceDBContext());
        modelBuilder.Configurations.Add(new JobDBContext());
        modelBuilder.Configurations.Add(new JobStatusDBContext());            
    }

    public WebDBContext()
    {
        Database.SetInitializer<WebDBContext>(new DropCreateDatabaseAlways<WebDBContext>());
    }

    public void Seed()
    {
        // seeds initial data into the database
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<Job> Jobs { get; set; }
    public DbSet<JobStatus> JobStatuses { get; set; }
    public DbSet<Quote> Quotes { get; set; }

BaseDBContext:
此类仅提供不特定于任何应用程序的通用上下文。这允许为项目之间可能常见的对象编写CRUD功能

public class BaseDBContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

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

    public BaseDBContext()
        : base()
    {
        Database.SetInitializer<BaseDBContext>(new DropCreateDatabaseIfModelChanges<BaseDBContext>());
    }

    public DbSet<BaseUser> Users { get; set; }
}

编辑2
Chris请求ConnectionString和My UserDBContext(下面有关于此的更多内容 - 非常重要的东西

  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Jobber.Web-20150105094927;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Jobber.Web-20150105094927.mdf" />
  </connectionStrings>

public class UserDBContext : DBBaseObject<User>
{
    // application-specific columns
    public UserDBContext()
        : base()
    {
        //HasOptional(r => r.Role)
        //    .WithMany(m => m.Users)
        //   .Map(x => x.MapKey("fkRoleID"))
        //    .WillCascadeOnDelete(false);

        ToTable("Users");
    }
}

开始解释这个......我正在开发一个处理所有“全局通用”结构和方法的应用程序框架,也就是说它处理所有逻辑上可以假定在应用程序之间通用的东西。

例如包含用户名和密码的用户对象。

框架与许多继承,抽象类和一些泛型的使用放在一起。如果不是这样的话,这或多或少就是这样:

框架:

Logan.Base
{
    Logan.Base.BaseObject  
    - defines common fields that all tables will always have (PK, auditing, etc)  

    Logan.Base.BaseUser  
    - defines common fields that user tables will have (username, password, etc)
}  
Logan.DBBase  
{
    Logan.DBBase.BaseUserDBContext  
    - defines C#->SQL data type mappings for the BaseUser along with CRUD functions  

    Logan.DBBase.DBBaseObject  
    - defines C#->SQL data type mappings for columns that all tables will always have  

    Logan.DBBase.DBContext  
    - defines a DbContext to be used in the DBBaseObject
}

Logan.Base

namespace Logan.Base
{
    public abstract class BaseObject
    {
        public Int64 PKey { get; set; }
        public Int64 CreatedBy { get; set; }
        public DateTime CreatedOn { get; set; }
        public Int64 ModifiedBy { get; set; }
        public DateTime ModifiedOn { get; set; }

        public BaseObject()
        {
            PKey = 0;
            CreatedBy = 0;
            ModifiedBy = 0;
        }
    }

    public abstract class BaseUser : BaseObject
    {
        public string EmailAddress { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public BaseUser()
        {
            EmailAddress = String.Empty;
            Password = String.Empty;
            FirstName = String.Empty;
            LastName = String.Empty;
        }        
    }
}

Logan.DBBase

namespace Logan.DBBase
{

    public abstract class DBBaseObject<T> : EntityTypeConfiguration<T>
        where T : BaseObject
    {

        public DBBaseObject()
            : base()
        {
            HasKey(p => p.PKey);
        }
    }

    public class BaseUserDBContext : DBBaseObject<BaseUser>
    {

        // common columns
        public BaseUserDBContext()
            : base()
        {
            Property(p => p.EmailAddress)
                .HasColumnName("sEmailAddress")
                .HasMaxLength(200)
                .IsRequired();

            Property(p => p.Password)
                .HasColumnName("sPassword")
                .HasMaxLength(255)
                .IsRequired();

            Property(p => p.FirstName)
                .HasColumnName("sFirstName")
                .IsRequired();

            Property(p => p.LastName)
                .HasColumnName("sLastName")
                .IsRequired();

            ToTable("Users");
        }

        // User CRUD functions that use the below DbContext go here
    }

    public class BaseDBContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

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

        public BaseDBContext()
            : base()
        {
            Database.SetInitializer<BaseDBContext>(new DropCreateDatabaseIfModelChanges<BaseDBContext>());
        }

        public DbSet<BaseUser> Users { get; set; }
    }
}

2 个答案:

答案 0 :(得分:2)

对我来说问题是我的表中有一个SQL_VARIANT类型列。一旦我将其更改为nvarchar,错误就消失了。

答案 1 :(得分:0)

我认为你的DBContext有几个问题。我会回到基础知识,一旦我进行了数据库初始化工作,我就会开始添加东西。首先,删除BaseDbContext并将WebDBContext更改为:

public class WebDBContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new CompanyDBContext());
        modelBuilder.Configurations.Add(new ClientDBContext());
        modelBuilder.Configurations.Add(new QuoteDBContext());
        modelBuilder.Configurations.Add(new RoleDBContext());
        modelBuilder.Configurations.Add(new UserDBContext());
        modelBuilder.Configurations.Add(new InvoiceDBContext());
        modelBuilder.Configurations.Add(new JobDBContext());
        modelBuilder.Configurations.Add(new JobStatusDBContext());            
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<Job> Jobs { get; set; }
    public DbSet<JobStatus> JobStatuses { get; set; }
    public DbSet<Quote> Quotes { get; set; }
}  
宝贝步骤。让它工作,然后我们可以添加其余的配置,如果它仍然是必要的