简体   繁体   中英

Converting SQL to LINQ to XML

I'm writing the following code to convert SQL to LINQ and then to XML:

SqlConnection thisConnection = new SqlConnection(@"Data Source=3BDALLAH-PC;Initial Catalog=XMLC;Integrated Security=True;Pooling=False;");
thisConnection.Open();

XElement eventsGive =
    new XElement("data",
        from c in ?????? 
        select new XElement("event",
            new XAttribute("start", c.start),
            new XAttribute("end",c.eend),
            new XAttribute("title",c.title),
            new XAttribute("Color",c.Color),
            new XAttribute("link",c.link)));

Console.WriteLine(eventsGive);

The name of the table is "XMLC" and I want to refer to it. How can I do that? When I put its name directly VS gives an error. Also when I say thisConnection.XMLC it doesn't work.

It sounds like you want to use Linq-to-Sql. In that case you'll need to create a data context. There are plenty of tutorials on that.

You don't need to use linq to sql, however. Your source can be any enumerable. A DataReader, for example:

using (DbDataReader rdr = cmd.ExecuteReader()) {


    from c in rdr.Cast<DbDataRecord>() 
    select new XElement("event",
        new XAttribute("start", c["start"]),
        new XAttribute("end",c["eend"]),
        new XAttribute("title",c["title"]),
        new XAttribute("Color",c["Color"]),
        new XAttribute("link",c["link"])));

}

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