c# - 将 SQL 转换为 LINQ to XML

标签 c# sql linq linq-to-sql

我正在编写以下代码将 SQL 转换为 LINQ,然后再转换为 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);

表的名称是“XMLC”,我想引用它。我怎样才能做到这一点? 当我直接输入它的名字时,VS 给出了一个错误。此外,当我说 thisConnection.XMLC 时,它不起作用。

最佳答案

听起来您想使用 Linq-to-Sql。在这种情况下,您需要创建一个数据上下文。有很多这方面的教程。

但是,您不需要使用 linq to sql。您的来源可以是任何可枚举的。 DataReader,例如:

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"])));

}

关于c# - 将 SQL 转换为 LINQ to XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656279/

相关文章:

c# - System.IO.IOException : "The file exists" when using System. IO.Path.GetTempFileName() - 解决方案?

mysql - 需要帮助优化 SQL 查询

sql - 获得两种不同条件下的计数

c# - 所有获取数据库对象的 linq 都应该用 try catch 包围吗?

c# - Console.Writeline 适用于 x86 但不适用于 x64

c# - 逐步调试时重写 ToString() 不能正常工作

sql - LINQ 版本的 SQL LIKE 语句

c# - 当大多数项目访问的数据库具有我无法更改的糟糕模式时,我如何对我的项目进行单元测试?

c# - 使用LINQ的 "into"关键字进行分组连接不返回集合

c# - ImmutableArray<T> 和 ImmutableList<T> 的区别