我有一个简单的DAL,它包含一个SalesEnquiry
对象,其中包含List<T>
个Vehicle
对象,用于处理传入的查询(XML)并将它们写入D B。到目前为止一切都很好。
但是,我正在编写另一个进一步处理此数据库中数据的应用程序,因此我想使用这些相同的DAL对象来检索和操作数据。
我没有返回传统的记录集并迭代它们,而是手动填充SalesEnquiry / Vehicle对象的每个属性,我想我可以将数据从SQL Server返回为XML并对其进行反序列化。我已经使用这种技术来处理传入的数据。
但是,我不确定是否/如何在SQL Server中构建适当的XML,或者我必须分两个阶段来构建它。
以下将以XML格式提取查询:
Select EnquiryID as 'enquiry/enquiryid',
EnquiryNo as 'enquiry/enquiryno',
CompanyName as 'enquiry/company'
From Enquiries e
Where e.EnquiryID = 23
For XML PATH
以下将以XML格式提取相关车辆:
Select VehicleID as 'vehicle/vehicleid',
VehicleReg as 'vehicle/vehiclereg'
From Vehicles v
Where v.EnquiryID= 23
For XML PATH
我所得到的XML是:
<?xml version="1.0" encoding="utf-8"?>
<enquiry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<enquiry_id>123</enquiry_no>
<enquiry_no>100004</enquiry_no>
<company>MyCompany</company>
<enquiry_no>100004</enquiry_no>
<vehicles>
<vehicle>
<vehicle_registration>ABC123</vehicle_registration>
</vehicle>
<vehicle>
<vehicle_registration>XYZ789</vehicle_registration>
</vehicle>
</vehicles>
</enquiry>
我可以在SQL Server中创建它,还是必须在DAL中手动执行此操作?
更新
根据Shunty的建议,我正在使用以下内容:
Select enquiry.EnquiryID as enquiry_id, enquiry.EnquiryNo, enquiry.CompanyName, VehicleID as [vehicle.vehicle_id], VehicleReg as [vehicle.vehicle_registration]
From Enquiries as enquiry
inner join Vehicles on Vehicles.EnquiryID = enquiry.EnquiryID
Where enquiry.EnquiryID = 23
For XML AUTO, ELEMENTS
..我可以接近,但我不在那里:
<?xml version="1.0" encoding="utf-8"?>
<enquiry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<enquiry_id>123</enquiry_no>
<enquiry_no>100004</enquiry_no>
<company>MyCompany</company>
<enquiry_no>100004</enquiry_no>
<vehicle>
<vehicle_registration>ABC123</vehicle_registration>
</vehicle>
<vehicle>
<vehicle_registration>XYZ789</vehicle_registration>
</vehicle>
</enquiry>
要成功反序列化,我需要将<vehicle>
元素置于<vehicles>
父元素下。必须有一种方法来鼓励SQL制作正确的XML ...
答案 0 :(得分:1)
使用标准内部联接,然后查看FOR {XML子句的AUTO(和ELEMENTS)关键字(在MSDN上)。我没有完全尝试过,但它看起来确实是你想要的。
答案 1 :(得分:1)
使用XML PATH的替代方法:
SELECT
EnquiryID AS enquiry_id,
EnquiryNo AS enquiry_no,
CompanyName AS company,
(
SELECT
VehicleReg AS vehicle_registration
FROM Vehicles
WHERE EnquiryID = e.EnquiryID
FOR XML PATH ('vehicle'), TYPE, ROOT('vehicles')
)
FROM Enquiries e
WHERE EnquiryID = 123
FOR XML PATH ('enquiry'), TYPE
返回:
<enquiry>
<enquiry_id>123</enquiry_id>
<enquiry_no>100004</enquiry_no>
<company>MyCompany</company>
<vehicles>
<vehicle>
<vehicle_registration>ABC123</vehicle_registration>
</vehicle>
<vehicle>
<vehicle_registration>XYZ789</vehicle_registration>
</vehicle>
</vehicles>
</enquiry>