我正在编写一个预先创建的数据库,并且我已经为表创建了DBSet定义。当前数据库继承自以前的系统,每个表包含超过100,000行数据(事务超过5年)。我们将它放入一个新的应用程序,移植数据。
因此,手动创建数据库,而不是代码优先。新类首先是代码,我们希望将这些表自动生成到表中。
我已经检查过,并且用户对db_owner访问我们用于数据库连接的数据库。该数据库也不在ReadOnly中。
以下是创建的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
我已经考虑过按其他文章添加配置
这不起作用。我也尝试过这个 Enable-Migrations -ContextTypeName BHI.WCMS.DAL.Partner.PartnerContext -EnableAutomaticMigrations
这也不起作用。当我将Context从Partner更改为Logging(一个100%代码优先的数据库)时,它会毫无问题地加载表。所以,这导致我做出以下假设:
所有这一切,我正在看这个,并没有能够创建表。因此,当前存在的表中似乎存在问题,或者数据库本身存在问题(没有__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()
对此的任何帮助将不胜感激。
由于 罗伯特
答案 0 :(得分:0)
好的,在与这里的其中一个人合作时,我们能够弄清楚发生了什么。
我的实体课程编码错误(我在一年内没有注意到它)
版本不正确
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
更正版本
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
我造成的核心问题
核心问题是,我没有密钥(尝试捕获并记录捕获),当我添加密钥时,我没有为每个变量定义访问器/ mutator方法({get;设置;})。一旦我添加了这些,它就创建了表,而没有任何问题进入已经创建的数据库。它还按照我的预期创建了__MigrationHistory表。