Entity Framework с десериализацией XML от N до N - PullRequest
0 голосов
/ 21 мая 2019

У меня есть пример XML-файла, подобный этому

<Root>
  <device>
    <identifiers>
       <identifier>
         <deviceId>D7091032721</deviceId>
       </identifier>    
     </identifiers>
     <companyName>Xundas</companyName>
     <deviceDescription>Bursh</deviceDescription>
  </device>
  <device>
   <identifiers>
       <identifier>
         <deviceId>D7091032721</deviceId>
       </identifier>    
     </identifiers>
     <companyName>Xundas</companyName>
     <deviceDescription>Xirulitos</deviceDescription>
  </device>
</Root>

Где у меня есть список идентификаторов, которые могут быть связаны с моим списком устройств, и для другого устройства у меня может быть тот же идентификатор.

Я создал подобную структуру EntityFrameWork

[XmlRoot ("Root")] открытый класс DeviceList {[XmlElement ("device")] public List Devices = new List ();}

public class Device
{
    public int Id { get; set; }

    [XmlElement("companyName")]
    public string CompanyName { get; set; }

    [XmlElement("brandName")]
    public string BrandName { get; set; }


    [XmlElement("deviceDescription")]
    public string DeviceDescription { get; set; }

    [XmlArray("identifiers")]
    [XmlArrayItem("identifier", typeof(Identifier))]
    public List<Identifier> Identifiers { get; set; }

    [XmlArray("productCodes")]
    [XmlArrayItem("fdaProductCode", typeof(Product))]
    public List<Product> ProductCodes { get; set; }
}

public class Identifier
{
    public int Id { get; set; }

    [XmlElement("deviceId")]
    public string Di { get; set; }

    [XmlElement("deviceIdIssuingAgency")]
    public string DeviceIdIssuingAgency { get; set; }

    public List<Device> Devices { get; set; }
}

public class Product
{
    public int Id { get; set; }
    [XmlElement("productCode")]
    public string ProductCode { get; set; }
    [XmlElement("productCodeName")]
    public string ProductCodeName { get; set; }
}

public class CatalogDevice : DbContext
{
    public CatalogDevice()
    {
        Database.SetInitializer(new Configuration());
    }

    public DbSet<Device> Devices { get; set; }
}

И в моем Семени я заполняю свою БД следующим образом

  byte[] byteArray = Encoding.UTF8.GetBytes(xml);
  using (var stream = new MemoryStream(byteArray))
  {
      StreamReader reader = new StreamReader(stream);
      XmlSerializer serializer = new XmlSerializer(typeof(DeviceList));
      var devices = (DeviceList)serializer.Deserialize(reader);
      context.Devices.AddRange(devices.Devices);
  }
  base.Seed(context);

Но когда мои данные заполняются вместо создания, просто в моем IdentifierDevices создается новыйстрока для идентификатора и для устройств Есть способ, когда у меня есть дублированная запись в Entity, чтобы просто вставить в мою таблицу N..N, чтобы создать строку в обеих таблицах?

...