我必须复制一组recodrs并将它们添加到带有新ID的数据库中。
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,虽然有正确的序列,但它们会进入db。如何解决?
我的实体类和映射:
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 :(得分:0)
问题在于提取ParentEntity
的方式。它被EF跟踪(我也认为SubEntities
也是如此),所以我尝试添加一个已被跟踪的集合。我不太了解EF在这种情况下的工作方式,但解决方案是:
var subEntities= ct.SubEntities
.Where(qf => qf.ParentEntityId == oldParentEntityId)
.AsNoTracking()
.ToList();