Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to sql Error "Data at the root level is invalid " for nullable xml column

I have Created a table like

CREATE TABLE [dbo].[tab1]( 
 [Id] [int] NOT NULL, 
 [Name] [varchar](100) NOT NULL, 
 [Meta] [xml] NULL, 


CONSTRAINT [PK_tab1] PRIMARY KEY CLUSTERED  
( 
     [Id] ASC 
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

When I am doing linq to sql query to fetch a data it throw an error "data at the root level is invalid linq". In further investigation I come to know that the meta column is null in that case. In real it is nullable Do I have to remove the nullable and set some blank root node as default or there is some another way to get rid of the error.


My linq Query which throws error

     var obj1= (from obj in dbContext.tab1s
  where obj.id== 123
select obj).FirstOrDefault<Tab1>();
like image 902
Mukesh Agarwal Avatar asked Dec 20 '25 00:12

Mukesh Agarwal


1 Answers

Under no circumstances will you receive this error if the value of an XML column is NULL.

You will, however, receive this error if the field contains malformed XML, as the error suggests.

SQL Server permits you to do this:

UPDATE tab1
SET Meta = 'blah'
WHERE id = 123

Obviously the string "blah" is invalid XML, but SQL Server still allows it. Linq to SQL does not, because it will try to actually load that XML into an XElement. If you run the query with this value in the column, you will get exactly the same error, Data at the root level is invalid.

In order to fix this error you need to fix the malformed XML that is present in the database.

like image 154
Aaronaught Avatar answered Dec 22 '25 15:12

Aaronaught



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!