数据库已创建,未添加新表

本文关键字:添加 新表 创建 数据库 | 更新日期: 2023-09-27 18:06:57

我正在编写一个预先创建的数据库,并且我已经为表创建了DBSet定义。当前数据库继承自以前的系统,每个表包含超过100,000行数据(事务超过5年)。我们把它放到一个新的应用程序中,移植数据。

所以,数据库是手动创建的,而不是先用代码创建的。新类首先是代码,我们希望这些表能够自动生成到表中。

我已经检查过了,并且用户对我们用于数据库连接的数据库具有db_owner访问权限。数据库也不是只读状态。

下面是创建的Context类:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BHI.WCMS.DAL;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;

namespace BHI.WCMS.DAL.Partner
{
    public class PartnerContext : DbContext
    {
        public PartnerContext()
            : base("partner")
        {
            //Configuration.LazyLoadingEnabled = false;
            Database.SetInitializer<PartnerContext>(new MigrateDatabaseToLatestVersion<PartnerContext, PartnerConfiguration>());
        }
        public PartnerContext(string ConnectionStringName)
            : base(ConnectionStringName)
        {
        }
        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //    modelBuilder.Entity<PartnerProfileServiceCenterTransaction>().Property(p => p.AmountDue).HasPrecision(8, 2);
        //    base.OnModelCreating(modelBuilder);
        //}
        public DbSet<WarrantyForms> WarrantyForms { get; set; }
        public DbSet<WarrantyFormLines> WarrantyFormLines { get; set; }
        public DbSet<WarrantyFormLineParts> WarrantyFormLineParts { get; set; }
        public DbSet<WarrantyFormLineReplacements> WarrantyFormLineReplacements { get; set; }
        public DbSet<PartnerProfile> PartnerProfiles { get; set; }
        public DbSet<PartnerProfileContactInfo> PartnerProfileContactInfos { get; set; }
        public DbSet<PartnerProfileCustomerAddress> PartnerProfileCustomerAddresses { get; set; }
        public DbSet<PartnerProfileServiceCenterTransaction> PartnerProfileServiceCenterTransactions { get; set; }
        public static PartnerProfile InsertPartnerProfile(PartnerProfile profile)
        {
            using (var db = new PartnerContext())
            {
                foreach (var addy in profile.BillingAddress)
                {
                    addy.DateCreated = DateTime.Now;
                    addy.DateModified = DateTime.Now;
                    db.PartnerProfileCustomerAddresses.Add(addy);
                    db.SaveChanges();
                }
                //profile.DateCreated = DateTime.Now;
                //profile.DateModified = DateTime.Now;
                //db.PartnerProfiles.Add(profile);
                //db.SaveChanges();
            }
            return profile;
        }   // end of  public static PartnerProfile InsertPartnerProfile(PartnerProfile profile)
        public static PartnerProfile UpdatePartnerProfile(PartnerProfile profile)
        {
            using (var db = new PartnerContext())
            {
            }
            return profile;
        }   // end of  public static PartnerProfile UpdatePartnerProfile(PartnerProfile profile)
        public static PartnerProfile SelectPartnerProfile(PartnerProfile profile)
        {
            using (var db = new BHI.WCMS.DAL.Partner.PartnerContext())
            {
            }
            return profile;
        }   // end of  public static PartnerProfile SelectPartnerProfile(PartnerProfile profile)
    }       // end of class WarrantyContext : DbContext
    internal sealed class PartnerConfiguration : DbMigrationsConfiguration<PartnerContext>
    {
        public PartnerConfiguration()
        {
            AutomaticMigrationsEnabled = true;
        }
    }
}           // end of namespace BHI.WCMS.DAL.Partner

我已经考虑过在其他文章中添加配置

  • EF自动迁移和播种的混淆-播种每个程序开始
  • http://www.scriptscoop.bid/t/1c411f565b56/tables - -不反映在数据库- - vs - 2013上使用代码-第一a.html

,这不起作用。我也试过运行这个启用- migrations -ContextTypeName bhh . wcms . dal . partner . partnercontext -EnableAutomaticMigrations

这也不起作用。当我将上下文从Partner更改为Logging(首先是100%代码的数据库)时,它会毫无问题地加载表。因此,这导致我做出以下假设:

    定义表的类文件没有问题
  1. 引用
  2. 文件的DBContext文件没有问题
  3. 因为我能够从数据库中检索旧表的数据,所以数据库
  4. 的用户名/密码没有问题。
  5. 因为用户帐户具有db_owner访问权限,所以数据库不应该有任何权限问题。

话虽这么说,我正在看这个,不能得到表创建。因此,当前存在的表中似乎有问题,或者数据库本身有问题(没有__MigrationHistory表)。

我得到的错误信息是:

    Exception: System.Data.Entity.Infrastructure.DbUpdateException
    Message: An error occurred while updating the entries. See the inner exception for details.
    Source: EntityFramework
       at System.Data.Entity.Internal.InternalContext.SaveChanges()
       at BHI.WCMS.DAL.Partner.WarrantyContext.InsertPartnerProfile(PartnerProfile profile) in c:'inetpub'Bissell SiteCore'Dev'Partners-Dev'BHI.WCMS'BHI.WCMS.DAL'Partner'WarrantyContext.cs:line 47
       at BHI.WCMS.ECommerce.BWS.Partner.MapServiceToObject(ServiceCenterResponse response) in c:'inetpub'Bissell SiteCore'Dev'Partners-Dev'BHI.WCMS'BHI.WCMS.ECommerce.BWS'Partner.cs:line 151
       at BHI.WCMS.ECommerce.BWS.Partner.BWSGetServiceCenterInfo(String accountNumber, String zipCode) in c:'inetpub'Bissell SiteCore'Dev'Partners-Dev'BHI.WCMS'BHI.WCMS.ECommerce.BWS'Partner.cs:line 48
    Nested Exception
    Exception: System.Data.Entity.Core.UpdateException
    Message: An error occurred while updating the entries. See the inner exception for details.
    Source: EntityFramework
       at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
       at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
       at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
       at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
       at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
       at System.Data.Entity.Internal.InternalContext.SaveChanges()
    Nested Exception
    Exception: System.Data.SqlClient.SqlException
    Message: Invalid object name 'dbo.PartnerProfileCustomerAddresses'.
    Source: .Net SqlClient Data Provider
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       at Glimpse.Ado.AlternateType.GlimpseDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
       at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
       at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
       at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
       at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()

如果有任何帮助,我将不胜感激。

谢谢罗伯特。

数据库已创建,未添加新表

好的,在与这里的一个家伙合作时,我们能够弄清楚发生了什么。

  1. 创建一个数据库,然后允许它在手动创建的数据库中创建更多的表(这就是我们在日志表上所做的)。
  2. 这个问题与上下文错误无关,而是我对细节的关注不够。

我的一个实体类编码不正确(我在一年内没有注意到它)

<<p> 错误的版本/strong>
public partial class WarrantyFormLineReplacements
{
    #region Class Variables
    public int in_WFLineReplacementID;
    public int in_WFlineId;
    public int in_WFId;
    [MaxLength(120)]
    public string vc_ModelNumber;
    public decimal dc_ReplacementCost;
    [MaxLength(255)]
    public string vc_InsertBy;
    public DateTime dt_InsertDate;
    [MaxLength(255)]
    public string vc_UpdateBy;
    public DateTime dt_UpdateDate;
    #endregion
}       // end of public partial class WarrantyFormLineReplacements
<<p> 修正版本/strong>
public partial class WarrantyFormLineReplacements
{
    #region Class Variables
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int in_WFLineReplacementID {get;set;}
    public int in_WFlineId { get; set; }
    public int in_WFId { get; set; }
    [MaxLength(120)]
    public string vc_ModelNumber { get; set; }
    public decimal dc_ReplacementCost { get; set; }
    [MaxLength(255)]
    public string vc_InsertBy { get; set; }
    public DateTime dt_InsertDate { get; set; }
    [MaxLength(255)]
    public string vc_UpdateBy { get; set; }
    public DateTime dt_UpdateDate { get; set; }
    #endregion
}       // end of public partial class WarrantyFormLineReplacements

我造成的核心问题

核心问题是,我没有Key (try catch和logging捕获),当我添加Key时,我没有为每个变量定义accessor/mutator方法({get;设置;})。一旦我添加了这些表,它就会毫无问题地将表创建到已经创建的数据库中。它还创建了我所期望的__MigrationHistory表。