我在dbContext中有两个相关的表,RunArea有很多运行。我想生成一个XML feed。
这是我的观点型号:
public class RunAreaViewModel
{
public string RunName { get; set; }
public string RunAreaName { get; set; }
}
我的控制员:
public ActionResult Test()
{
var theRuns =
(from r in db.Runs
join ra in db.RunAreas on r.RunRunAreaID equals ra.ID
select new RunAreaViewModel
{
RunName = r.RunName,
RunAreaName = ra.RunAreaName
}).ToList();
XmlSerializer sSubmit = new XmlSerializer(typeof(RunAreaViewModel));
StringWriter sw = new StringWriter();
XmlWriter xw = XmlWriter.Create(sw);
sSubmit.Serialize(xw, theRuns);
var xml = sw.ToString();
return Content(xml, "application/xml");
/*return View(theRuns);*/
}
这是我现在想要生成的一个节点,
<Run>
<RunName>Wishing Well</RunName>
<RunAreaName>The Maze</RunAreaName>
</Run>
使用代码生成Razor View没有问题,但我无法生成XML Feed。我收到一个错误:
无法将类型为'System.Collections.Generic.List`1 [namespace.Models.RunAreaViewModel]'的对象转换为类型namespace.Models.RunAreaViewModel'。
任何想法,
答案 0 :(得分:1)
构建序列化程序时,您指定的是typeof(RunAreaViewModel)
,但您实际尝试序列化的是typeof(List<RunAreaViewModel>)
。尝试创建这样的序列化器:
XmlSerializer sSubmit = new XmlSerializer(typeof(List<RunAreaViewModel>));