代码之家  ›  专栏  ›  技术社区  ›  user6728767

我们必须显式地添加到数据库上下文吗?

  •  0
  • user6728767  · 技术社区  · 8 年前
    public class Practice
    {
        public List<Participation> Participation { get; set; }
    }
    
    public class Participation
    {
        public string Id { get; set; }
        public virtual Practice Practice { get; set; }
    }
    
    public void test()
    {
        var practice = _ctx.Practice.SingleOrDefault(p => p.Id == practiceId);
        practice.Participations.AddRange(NewParticipations);
        _ctx.Participation.AddRange(NewParticipations)
        await _ctx.SaveChangesAsync();
    }
    

    如果我有上述内容,我需要测试函数中的第三行来保存新的参与,还是practice.participations.addrange()隐式处理?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Jan Paolo Go vikomall    8 年前

    practice.Participations.AddRange 应该够了。

    如果从已被上下文跟踪的实体的导航属性引用新实体,则该实体将被发现并插入到数据库中。

    来源: https://docs.microsoft.com/en-us/ef/core/saving/related-data#adding-a-related-entity

    你可以这样观察它…

    var practice = _ctx.Practice.SingleOrDefault(p => p.Id == practiceId);
    
    practice.Participations.AddRange(NewParticipations);
    
    Debug.WriteLine(_ctx.Participation.Count()); //note count
    
    await _ctx.SaveChangesAsync();
    
    Debug.WriteLine(_ctx.Participation.Count()); //count increased
    
        2
  •  0
  •   Paul    8 年前

    无论哪种方式,您都应该能够将新数据添加到数据库中。如果在上下文中添加,则需要在新的Engulink对象中设置外键,以便对实践对象存在链接。

    推荐文章