将SQL查询转换为LINQ以获取列值作为xml字符串

时间:2018-12-13 05:49:42

标签: linq linq-to-sql linq-to-xml

我在SQL中有以下查询。 我必须在LINQ中编写相同的查询,该查询将以XML字符串格式提供与SQL查询相同的输出。

此select语句以XML形式返回列值

SELECT Student.Name 
    FROM   StudentCategoryAssociation Assoc
     JOIN Student ON Assoc.CategoryId = Student.Id
 for xml raw('Category'), root('StudentCategories'), type

此输出为:

<StudentCategories>
  <Category Name="StudentCategory" />
  <Category Name="Light" />
</StudentCategories>

1 个答案:

答案 0 :(得分:0)

要获得所需的输出,它可能不仅仅需要一个简单的Linq。在以下示例中,我尝试用List来模拟您的数据库。

var result = new StudentCategories
               {  
                  Category = associationList
                            .Join(studentlist,
                            a=>a.Id,
                            s=>s.Id,
                            (a,s)=>new Category{Name=s.Name}).ToList()
              };
var serializer = new XmlSerializer(typeof(StudentCategories));
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var settings = new XmlWriterSettings{OmitXmlDeclaration = true,Indent=true};
string xmlString;

using(var sww = new StringWriter())
using(XmlWriter writer = XmlWriter.Create(sww,settings))
{
  serializer.Serialize(writer, result,emptyNamespaces);
  xmlString = sww.ToString(); // Your XML
}

其中“类别”和“学生类别”定义为

[XmlRoot(ElementName="Category")]
public class Category {
    [XmlAttribute(AttributeName="Name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName="StudentCategories")]
public class StudentCategories {
    [XmlElement(ElementName="Category")]
    public List<Category> Category { get; set; }
}

输出应为

<StudentCategories>
  <Category Name="StudentCategory" />
  <Category Name="Light" />
</StudentCategories>