开发者

populating an Entity DataModel from XML using Linq

I have a C# .net 3.5 application using an ADO.NET Entity D开发者_JAVA技巧ata Model. I am loading the contents for a given database entry from an XML file. What's the best method to convert a List<String> from the XML to an EntityCollection<>?

The XML looks like this:

<Task>
    <Name>Test Task</Name>
    <SerialNumbers>
        <Serial>12345678901</Serial>
        <Serial>98765432101</Serial>
    </SerialNumbers>
</Task>

The database looks like this:

task { [int, pk]TaskID }
criteria_serialnumber { [int, pk]SerialNumberID, [string]SerialNumber }
task_serialnumber { [int, pk]SerialNumberID, [int, pk]TaskID }

The C# code looks like this:

using (XmlTextReader xml = new XmlTextReader(task_file))
{
    XElement x = XElement.Load(xml);

    // this works great.
    task.Name = x.Element("Name").Value;

    // How do I convert from List<String> to EntityCollection<criteria_serialnumber> ? 
    task.SerialNumbers = (from i in x.Element("SerialNumbers").Elements("Serial") select i.Value).ToList();
}


You do not need to convert a List<string> to a EntityCollection<criteria_serialnumber>. You simply have to add each element to the existing EntityCollection:

var serialNumbers = x.Element("SerialNumbers").Elements("Serial")
                     .Select(sn => sn.Value).ToList();

foreach (var serialNumber in serialNumbers)
    task.SerialNumbers.Add(new SerialNumber { SerialNumber = serialNumber });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜