我有兩個實體:Project和StepImplementation。 StepImplementation對項目表有一個FK。 BulkInsert:INSERT語句與FOREIGN KEY約束衝突
我需要添加一個包含500個步驟的新項目到數據庫。如果我使用一個簡單的EntityFramework - 我沒有問題,但據我在SQL Profiler中的500個步驟,我觀察到500個插入。所以我試圖用一系列EntityFramework.BulkInsert來添加一個新項目。
public Project CreateProjectCopy(Project project)
{
var newProject = this.repositoryScope.Projects.Value.Add(new Project()
{
Name = project.Name,
BddFrameworkType = project.BddFrameworkType,
Domain = project.Domain,
IsActive = project.IsActive,
IsPrivate = project.IsPrivate,
ProjectKey = this.GenerateProjectKey(),
SavingMode = project.SavingMode
});
this.repositoryScope.Projects.Value.SaveChanges();
var checkProjectExists = this.repositoryScope.Projects.Value.GetFirstOrDefault(x => x.Id == newProject.Id);
var steps = project.StepImplementations.Select(s => new StepImplementation()
{
DocComment = s.DocComment,
StepImplementationText = s.StepImplementationText,
Project = checkProjectExists
}).ToList();
this.repositoryScope.StepImplementations.Value.AddRange(steps);
this.repositoryScope.StepImplementations.Value.SaveChanges();
newProject.Branches = this.treeManager.CopyAll(project);
return newProject;
}
public virtual void AddRange(List<T> entities)
{
this.context.BulkInsert(entities, new BulkInsertOptions { SqlBulkCopyOptions = SqlBulkCopyOptions.CheckConstraints, BatchSize = entities.Count() });
}
在的AddRange方法,我得到一個錯誤:「INSERT語句衝突與外鍵約束
FK_dbo.StepImplementation_dbo.Project_Project_Id". The conflict occurred in database "RelimeDB", table "dbo.Project", column 'Id'. The statement has been terminated.
但是我有意加入checkProjectExists變量來檢查該項目存在於數據庫中也。的AddRange方法之前,我檢查新近通過SQL管理Studio中添加項目,它是可用的。那麼,爲什麼BulkInsert不能添加的步驟,如果純粹的EntityFramework能?
你'StepImplementations'類可能上有一個 「專案編號」 屬性,嘗試設置而不是/以及'Project'屬性。我猜'BulkInsert'不看子對象。 –
此外,在繼續之前,你應該真的在檢查'checkProjectExists'爲null,或者,如果你知道它總是在那裏,使用'First'或'Single'而不是'FirstOrDefault' –
在我的StepImplementation類Project是虛擬的:''公共虛擬項目項目{get;組; }'我不能在這種情況下設置Project_Id,我得到一個錯誤。 – Stivin