Json 进入带有重复项的 EF

Json into EF with duplicates

我有以下示例 JSON(已简化):

{
   "programmes":[
      {
             "programmeID":"163",
             "title":"Programme 1",
             "color":"#ff5f57",
             "moderators":[
                {
                   "moderatorID":"27",
                   "name":"Moderator 1",
                }
             ]
          },
          {
             "programmeID":"153",
             "title":"Programme 2",
             "color":"#ff5f57",
             "moderators":[
                {
                   "moderatorID":"27",
                   "name":"Moderator 1",
                }
             ]
          },

       ]
}

我想转换成以下对象:

    public class Programme
    {
        [Key]
        public string programmeID { get; set; }
        public string title { get; set; }

        //Navigational Property
        public virtual ICollection<Moderator> moderators { get; set; }
    }

    public class Moderator
    {
        [Key]
        public string moderatorID { get; set; }
        public string name { get; set; }

        //Navigational Property
        public virtual ICollection<Programme> programmes { get; set; }
    }

一切都很好,对象看起来很棒,填充正确,但是当尝试保存到数据库时出现此错误:

The instance of entity type 'Moderator' cannot be tracked because another instance with the key value '{moderatorID: 27}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

调用 .Add 程序列表时发生此错误:

List<Programme> programmes;
programmes = JsonSerializer.Deserialize<List<Programme>>(JSONcontent);
//... db init
db.AddRange(programmes);

我知道版主 (ID=27) 有口是心非,但我认为这在 JSON 中是很正常的模式。我可以做一些解决方法,但想知道是否有任何最佳实践如何直接在 EF 中处理这个问题?

您不能添加 children 您是通过反序列化创建的,作为现有的。解决方案之一是首先找到已存在的 children

List<Programme> programmes = JsonSerializer.Deserialize<List<Programme>>(JSONcontent);

foreach (var program in programmes)
{
var moderators=new List<Moderator>();
foreach (var moderator in program.moderators)
{
     var existingModerator=db.Moderators.FirstOrDefault(i=> 
                 i.moderatorId=moderator.moderatorId);
    moderators.Add(existingModerator);
}
  programm.moderators=moderators;
}
db.AddRange(programmes);

但我通常更喜欢为多对多关系创建显式 class。它将使您的所有代码更加简单。