能否干预LINQPad对SQL Server XML列的代码生成?
Great question! You've hit on a common mismatch between SQL Server's XML support and how Linq-to-SQL maps those columns by default. Let's break down why this happens and how you can fix it by adjusting the code generation process.
Why the Error Occurs
SQL Server's xml data type allows XML fragments (multiple root elements) (like <a>1</a><a>2</a>), but Linq-to-SQL and LINQPad automatically map these columns to XElement by default. The problem? XElement requires a single root node—so when it tries to parse a multi-root fragment, it throws that "multiple root elements" error.
Yes, You Can Intervene in the Code Generation!
Here are the most straightforward ways to adjust the mapping:
1. Modify the DBML File (Linq-to-SQL)
If you're using a DBML file for your Linq-to-SQL model:
- Open the DBML file (either in Visual Studio's designer or a text editor like Notepad++).
- Locate the
<Column>element for your XML column (e.g.,<Column Name="C1" Type="System.Xml.Linq.XElement" ... />). - Change the
Typeattribute fromSystem.Xml.Linq.XElementtoSystem.Xml.Linq.XDocument. - Save the DBML and regenerate your data context code.
XDocument is designed to handle XML content with multiple root nodes, so this will eliminate the error entirely.
2. Adjust the Schema in LINQPad
For LINQPad users:
- After connecting to your database, right-click the table with the XML column and select Edit Schema.
- In the schema editor, find your XML column (
C1in your example). - Change the Type dropdown from
XElementtoXDocument. - Save the schema changes, then re-run your query—no more root element errors!
3. Manual Conversion (Quick Fix Without Changing Mappings)
If you can't modify the schema/mapping right now, you can work around the issue by converting the XML content manually in your query:
var tempData = from t in Temp select new { t.ID, MultiRootXml = XDocument.Parse(t.C1.ToString()) };
This converts the XElement-bound value to a string first, then parses it into an XDocument that supports multiple roots. Note that this is a per-query fix, so modifying the mapping is better for long-term use.
Key Note
XDocument is fully compatible with both single-root XML documents and multi-root fragments, so switching to it is a safe choice even if your XML column sometimes has single-root content.
内容的提问来源于stack exchange,提问作者Rm558

