以XDocument的形式给出以下XML结构:
<Header><person><ID>0888-123-45</ID><Name>Joe</Name><LocationID>Loc1</LocationID><LocationName>New York</LocationName><CarName>Honda</CarName><CarYear>2000</CarYear></person><person><ID>199-20-333</ID><LocationID>My House</LocationID><LocationName>My House</LocationName><CarName>BMW</CarName><CarYear>2011</CarYear></person></Header>
涉及3个实体:
人:
汽车:
位置:
我想要实现的是以下步骤:
这就是我所拥有的,它抛出了一个错误,因为查询是Linq to Entities和Linq to XML的混合。我感谢任何有关更好的解决方法的见解和建议。对于循环没有,因为使用for循环解析XDocument很慢。
Dim fileLocs = (From p In xmlDoc.<Header>.<Person>
Select New location With {.locID = Guid.NewGuid(), _
.locationID = If(p.<LocationID> Is Nothing, Nothing, p.<LocationID>.Value), _
.locLabel = If(p.<LocationName> Is Nothing, Nothing, p.<LocationName>.Value)})
Dim filteredFileLocs = From l In fileLocs
Where l.locationID IsNot Nothing AndAlso l.locationID <> "" AndAlso
(From loc In ctx.locations
Where loc.locationID = l.locationID AndAlso loc.locLabel = l.locLabel
Select loc).Count = 0
Select l
Dim sysLocs = (From loc In ctx.locations Select loc)
Dim allLocs = filteredFileLocs.Union(sysLocs)
Dim pers As IEnumerable(Of person) = (From p In xmlDoc.<Header>.<Person>
Select New Person With {.personID = Guid.NewGuid(), .ID = p.Element(XName.Get("ID")).Value, _
.locID = If(p.<locationID> IsNot Nothing AndAlso p.<locationID>.Value <> "", CType(Nothing, Guid?), _
(From sl In allLocs
Where sl.locationID = p.Element(XName.Get("LocationID")).Value AndAlso
sl.locLabel = p.Element(XName.Get("LocationName")).Value
Select sl.locID)), _
.Name = p.Element(XName.Get("Name")).Value})
For Each l In filteredFileLocs
ctx.locations.AddObject(l)
Next
For Each p In pers
ctx.persons.AddObject(p)
Next
错误在线Dim pers:“指定的演员表无效。”
答案 0 :(得分:0)
我注意到的是设置了.locID的子句,
(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value
AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value Select sl.locID)
返回一个ienumberable并将其分配给.LocID这是一个GUID,因此应该是错误原因,你需要添加FirstOrDefault,First,SingleOrDefault或Single这样
(From sl In allLocs Where sl.locationID = p.Element(XName.Get("LocationID")).Value
AndAlso sl.locLabel = p.Element(XName.Get("LocationName")).Value _
Select sl.locID).FirstOrDefault()