实体框架核心2.1 - 保存一个到多个相关记录时出错

时间:2018-06-18 12:50:46

标签: c# sql-server entity-framework

我已经配置了一对多关系,如下所述。但是,SQL表中没有设置实际的外键。

//Parent Entity
public partial class Summary
{
    public Summary()
    {
        DetailRecords = new HashSet<Details>();
    }
    public Guid DocUnid { get; set; }
    //Some other columns
    public ICollection<Details> DetailRecords { get; set; }
}

//Child Entity
public partial class Details
{
    public Guid DocUnid { get; set; }
    public Guid ParentRecordUnid { get; set; }
    //Some other columns
    public Summary SummaryRecord { get; set; }
}

//Code from DbContext class
modelBuilder.Entity<Details>(entity =>
{
    entity.HasKey(e => e.DocUnid);
    entity.ToTable("Details", "App");

    entity.Property(e => e.DocUnid)
        .HasColumnName("DocUNID")
        .HasDefaultValueSql("(newid())");

    entity.Property(e => e.ParentRecordUnid).HasColumnName("ParentRecordUNID");

    entity.HasOne(x => x.SummaryRecord)
    .WithMany(y => y.DetailRecords)
    .HasForeignKey(z => z.ParentRecordUnid);
});

modelBuilder.Entity<Summary>(entity =>
{
    entity.HasKey(e => e.DocUnid);

    entity.ToTable("Summary", "App");

    entity.Property(e => e.DocUnid)
        .HasColumnName("DocUNID")
        .HasDefaultValueSql("(newid())");
    //Tried below code also
    //entity.HasMany(x => x.DetailRecords)
    //.WithOne(y => y.SummaryRecord)
    //.HasForeignKey(z => z.ParentRecordUnid);
});


//Code to save records
public async void Save(ViewModel viewModel)
{
    var summary = Mapper.Map<Summary>(viewModel);
    foreach (Details row in summary.DetailRecords)
    {
        //Setting some other column values here
    }
    await _unitOfWork.Summaries.AddAsync(summary);
    await _unitOfWork.CompleteAsync(default(CancellationToken));
}

它说“执行DbCommand失败”,然后是“System.InvalidOperationException:无效操作。连接已关闭”。

我不确定我在这里做错了什么。我只是想知道EF Core 2.1目前是否支持这种操作。

更新

我删除了导航属性以确保错误与一对多关系无关。我仍然收到以下错误。

  

App&gt;失败:Microsoft.EntityFrameworkCore.Database.Transaction [20205]   应用&GT;使用事务发生错误。   App&gt; System.InvalidOperationException:此SqlTransaction有   完成;它不再可用。应用&GT;在   System.Data.SqlClient.SqlTransaction.ZombieCheck()App&gt;在   System.Data.SqlClient.SqlTransaction.Commit()App&gt;在   Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Commit()

0 个答案:

没有答案