2016-11-28 76 views
0

我必須複製recodrs集合並將它們添加到帶有新ID的db。Npgsql上的EF核心AddRange指數

var subEntities= ct.SubEntities.Where(qf => qf.ParentEntityId == oldParentEntityId).ToList(); 
subEntities.ForEach(qf => { qf.ParentEntityId = newParentEntityId; qf.Id = default(int); }); 
ct.SubEntities.AddRange(subEntities); 

AddRange已運行的所有實體subEntities有尷尬的ID,如-2147482647,他們進入分貝,雖然有一個正確的順序。如何解決它?

我的實體類和映射:

public class SubEntity 
{ 
    public int Id { get; set; } 
    public Guid ParentEntityId { get; set; } 
    public virtual ParentEntity ParentEntity { get; set; } 
    //props 
} 

public class ParentEntity 
{ 
    public Guid Id { get; set; } 
    public virtual List<SubEntity> SubEntities { get; set; } 
    //props 
} 

//OnModelCreating 
builder.Entity<ParentEntity>() 
    .HasMany(q => q.SubEntities) 
    .WithOne(qf => qf.ParentEntity) 
    .HasForeignKey(qf => qf.ParentEntityId) 
    .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade); 
+0

您是否嘗試過使用Select方法創建新實例?我需要知道你的實體的映射,你可以發佈該代碼嗎? –

+0

@ H.Herzl是的,我只是試圖從源代碼集合中選擇新的實例並添加它們 - 都一樣。 – Slip

+0

我需要查看fulll代碼才能保存更改,您可以發佈嗎? –

回答

0

問題是提取ParentEntity的方式。它由EF跟蹤(我也猜到了SubEntities),所以我試圖添加一個已經被跟蹤的集合。我不太瞭解EF如何在這種情況下工作,但解決方案是:

var subEntities= ct.SubEntities 
    .Where(qf => qf.ParentEntityId == oldParentEntityId) 
    .AsNoTracking() 
    .ToList();