情况就是这样:我们有两个数据库,一个叫做生产,另一个叫做测试。
我正在生成数据库中插入实体,并启用了以下属性:
Property(c => c.MyPrimaryKey).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
但是我需要使用相同的主键在另一端复制这些信息,所以我可以删除并重新插入所有内容,而不必担心相关信息的状态。
我有两张桌子:
A B C
1 1X X
1Y Y
所以我想更新对象“X”而不破坏它与对象“1”的关系。我可以根据其他信息链接这些对象,但这比仅使用相同的主键删除和插入要复杂得多。
这是执行此操作的代码:
//Turn on identity insert
var setIdentityOnCommands = new List<string>(new[]
{
@"SET IDENTITY_INSERT Tab_relatorios ON",
@"SET IDENTITY_INSERT Tab_views ON",
@"SET IDENTITY_INSERT Tab_views_colunas ON",
@"SET IDENTITY_INSERT Tab_views_comandos ON",
});
//Get the information from production database
using (var source = new OuroReportsContext(sourceConnectionString))
{
sourceReports =
source.Reports
.Include("Views.Config.ConfigColumns.ViewColumn")
.Include("Views.Config.ConfigGroups.ViewColumn")
.Include("Views.ViewColumns")
.Where(c => idReports.Contains(c.IdReport))
.ToList();
sourceCommands =
source.Views.Include("Command")
.Include("Report")
.Where(c => idReports.Contains(c.Report.IdReport))
.ToList().Select(c => c.Command).ToList();
}
//Run the commands above in the target(test database)
using (var context = new OuroReportsContext(targetConnectionString))
{
foreach (var command in setIdentityOnCommands)
{
context.Database.ExecuteSqlCommand(command);
}
}
//Create a new scope
using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
{
using (var target = new OuroReportsContext(targetConnectionString))
{
//Execute a procedure that will make the delete job
idReports.ForEach(c => target.Database.ExecuteSqlCommand("exec sp_mng_Deletar_Relatorio " + c));
//Below is the inserting and checking process
sourceReports.ForEach(c => c.ReportGroup = target.ReportGroups
.SingleOrDefault(d =>
d.ReportGroupDescription.Equals(groupName)));
foreach (var command in sourceCommands)
{
target.Commands.AddOrUpdate(c => c.CommandName, command);
}
sourceReports
.ForEach(c => c.Views.Command = target.Commands.Single
(d => d.CommandName.Equals(c.Views.SqlCommandName)));
sourceReports.ForEach(c => target.Reports.Add(c));
sourceReports.ForEach(c => c.Views.Config.ToList().ForEach(d => configNames.Add(d.ConfigName)));
//Verify if has any error.
var errors = target.GetValidationErrors();
if (!errors.Any())
{
target.SaveChanges();
scope.Complete();
}
}
}
问题是:它不起作用= [。继续使用标识主键
插入对象