关于EFCORE关联表新增时出现的错误Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HM2L9PKHGR69",

最近再用ABP做项目,也是第一次用.net core做实际的项目,中间遇到了各种问题,记录一下其中一个问题

在做新增时使用了core first关联表新增

在主表实体中加入明细信息

public virtual ICollection<BT_Inv_Stockin_Detail> BT_Inv_Stockin_Detail { get; set; }

在明细中加入主表的实体

public virtual BT_Inv_Stockin BT_Inv_Stockin { get; set; }

然后再DBContext中重写OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //先调用基类的OnModelCreating方法,设置数据库中其它表和实体的映射关系
            base.OnModelCreating(modelBuilder);
// 设置BT_Inv_Stockin和BT_Inv_Stockin_Detail主从表关系
            modelBuilder.Entity<BT_Inv_Stockin>(entity =>
            {
                entity.HasMany(x => x.BT_Inv_Stockin_Detail)//设置BT_Inv_Stockin可以通过属性BT_Inv_Stockin_Detail可以找到多个BT_Inv_Stockin_Detail实体,一对多关系
                .WithOne(x => x.BT_Inv_Stockin)//设置BT_Inv_Stockin_Detail可以找到一个BT_Inv_Stockin,表示多对一关系
                .HasPrincipalKey(p => p.Id)//设置BT_Inv_Stockin主表的关系键
                .HasForeignKey(l => l.EntryID)//设置BT_Inv_Stockin_Detail从表的关系键
                .OnDelete(DeleteBehavior.ClientSetNull);//设置级联删除效果
            });
        }

在使用时将包含主表和明细信息的json转换,使用AutoMap对应,新增主表就可以实现主表明细同时新增,并且可以对应新增外键

var stockin = mapper.Map<BT_Inv_Stockin>(dto);
var stockdetailin = mapper.Map<List<BT_Inv_Stockin_Detail>>(dto.BT_Inv_Stockin_Detail);
var date = await stockInRepository.InsertAsync(stockin);

这样做,虽然实现了增加的效果,但是swagger包了500的错误

关于EFCORE关联表新增时出现的错误Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HM2L9PKHGR69",

 

 

 调试也没有catch出来,然后在控制台找到了报错

关于EFCORE关联表新增时出现的错误Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HM2L9PKHGR69",

 

 

 

 

 

 

 大概意思是因为实体是主表和明细表之后项目引用导致了内循环,从前面的报错信息查不到资料,后来从Newtonsoft.Json入手,找到了解决方案:

主要问题还是落在Self referencing loop detected for property这里

方法很简单,

在BT_Inv_Stockin_Detail导航属性上加[JsonIgnore]特性来忽略该属性。

[JsonIgnore]
public virtual BT_Inv_Stockin BT_Inv_Stockin { get; set; }

当然,也可以去掉关联关系,不使用关联新增,但是这样治标不治本。

 

解决方案参考地址:https://www.cnblogs.com/taoshengyujiu/p/7725510.html

上一篇:SEH exception with code 0xc0000005 thrown in the test body


下一篇:Exception thrown on Scheduler.Worker thread. Add `onError` handling