动态地将DataSet映射到StringTemplate [英] Dynamically Map a DataSet to StringTemplate

查看:239
本文介绍了动态地将DataSet映射到StringTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows服务通知项目(.NET 4.0)中使用 StringTemplate 。我的目标是读取和处理定义查询和stringtemplate的XML文件。然后该类将从DataTable的结果绑定到用于发送电子邮件的模板。下面是一个XML代码段,LINQ语句和C#来进行绑定。

I am using StringTemplate in a Windows Service notification project (.NET 4.0). My objective is to read in and process XML files that define a query and a stringtemplate. The class then binds the results from a DataTable into the template for emailing. Below is an XML snippet and the LINQ statement and the C# to do the binding.

<!-- XML Data Original-->
<Items>
  <Item>
    <Query>
       Select name, title, date from People;
    </Query>
    <Template>
        Welcome $name to $title$ on $date$.
    </Template>
  </Item>
</Items>

 var dataTable = database.GetQuery(query);
 var data = (from dataRow in dataTable.AsEnumerable()
            select new
            {
               Name = dataRow.Field<string>("Name"),
               Title = dataRow.Field<string>("Title"),
               Date = dataRow.Field<DateTime>("Date")
            }).Distinct();
  stringTemplate.SetAttribute("Name", data.Name);
  stringTemplate.SetAttribute("Title", data.Title);
  stringTemplate.SetAttribute("Date", data.Date);

问题是上面的C#是静态的,我想让它动态。那么如果我需要在XML查询元素和相应的模板字段中添加另一个字段呢?

The problem is the above C# is static, I would like to make it dynamic. That is what if I need to add another field in the XML query element and a corresponding template field?

<!-- XML Data Modified-->
<Items>
  <Item>
    <Query>
       Select name, title, date, location from People;
    </Query>
    <Template>
        Welcome $name to $title$ on $date$ at $location$.
    </Template>
  </Item>
</Items>

DataTable包含新列,但我的LINQ语句和绑定代码没有。我的问题是我可以采取什么策略来将DataTable中的数据动态地绑定到我的stringtemplate?注意我目前正在使用LINQ,但解决方案并不一定要。

The DataTable contains the new column, however my LINQ statement and binding code does not. My question is what strategy could I employ to fetch and bind the data from the DataTable to my stringtemplate dynamically? Note I am currently using LINQ but the solution does not have to.

推荐答案

并在String Template文件中迭代集合。我也以同样的方式处理单个记录static,但是我在Linq语句上使用了FirstOrDefault过滤器。

The approach I took is not projecting into an anonymous type and in the String Template file iterating over the collection. I also treat a single record "static" in the same manner but I use a FirstOrDefault filter on the Linq statement.

C#:

var dataTable = database.GetQuery(query);
var data = (from dataRow in dataTable.AsEnumerable()
            select dataRow);
stringTemplate.SetAttribute("dynamic", data);

模板:

$dynamic:{ d |
Welcome $d.name$ to $d.title$ on $d.date$ at $d.location$
}$

这篇关于动态地将DataSet映射到StringTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆