简体   繁体   中英

query xml string using LINQ

I have a table like this

Table (Id decimal,XMLContent XML)

now I want to query records that have specific Type this is my Code

 public ActionResult Index(int? id,FormCollection frm)
    {

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ViewBag.FormId = id;
        ViewBag.FormName = db.Forms.Find(id).Name ;
        var xMLDatas = db.XMLDatas.Include(x => x.Form).Where(x=>x.FormId==id).AsQueryable();
        foreach (string item in frm)
        {
            if (item.StartsWith("xml-") && !string.IsNullOrEmpty( Request.Form[item]))
            {
                string i = item.Replace("xml-", "");
                string value = Request.Form[item];
                xMLDatas = xMLDatas.Where(x => x.XMLContent.Contains("<" + i + "[^>]*>"+value+"</" + i + ">")).AsQueryable();
            }

        }
        return View(xMLDatas.ToList());
    }

but I got this error message on return

Disallowed implicit conversion from data type xml to data type nvarchar, table 'dbo.XMLDatas', column 'XMLContent'. Use the CONVERT function to run this query.

You can't call Contains("<" + i + "[^>]*>"+value+"</" + i + ">")) on XMLContent as sql type for that column is XML and not NVARCHAR .

Basically you can call Contains on something that is a string or implicitly converted to string by SQL Server.

But you can try to work around it on server side. Try to load XML from the DB first:

var xMLDatas = db.XMLDatas.Include(x => x.Form).Where(x=>x.FormId==id).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM