如何在ASP.NET 5 MVC中没有模型的情况下从查询中访问数据
我试图使用EF7在控制器内执行查询并在表中显示数据。
这是我的模特:
public class Resources { public int id { get; set; } public string name { get; set; } public string descr { get; set; } public string resourcePath { get; set; } public string method { get; set; } public string format { get; set; } public virtual ICollection Tags { get; set; } } public class MeasureSets { public int id { get; set; } public string name { get; set; } public string descr { get; set; } public string userName { get; set; } public bool isPublic { get; set; } public virtual ICollection Tags { get; set; } } public class MeasureTags { public int id { get; set; } public string name { get; set; } public string userName { get; set; } public bool isPublic { get; set; } public int sortOrder { get; set; } [ForeignKey("MeasureSets")] public int msId { get; set; } public virtual MeasureSets ms { get; set; } public virtual Resources res { get; set; } }
这是控制器中的连接查询:
//get users measure sets var m_sets = from t in _context.MeasureTags join s in _context.MeasureSets on t.ms.id equals s.id where s.userName == User.Identity.Name select new { id = t.id, set = s.name, tag = t.name, res = t.res.name }; return View(m_sets.ToArray());
在视图中我有一个foreach循环,它能够正确地提取每一行而不是列。 错误: ‘object’不包含’id’的定义(item.id)
@foreach (var item in Model) { string tagid = "tag" + item.id; @item.set @item.tag @item.res } }
我还为结果添加了一个额外的模型,但仍然没有成功。 错误是‘ManageTagTableModel’不包含’GetEnumerator’的公共定义
public class TagTable { public int id { get; set; } public string set { get; set; } public string tag { get; set; } public string res { get; set; } } public class ManageTagTableModel : IEnumerable { public IEnumerator GetEnumerator() { return ((IEnumerable)TagTable).GetEnumerator(); } }
问题是:如果可能的话,如何在不需要其他模型的情况下访问“新的”通用对象属性?
您需要将查询投影到TagTable
新实例中
var m_sets = from t in _context.MeasureTags join s in _context.MeasureSets on t.ms.id equals s.id where s.userName == User.Identity.Name select new TagTable { id = t.id, set = s.name, tag = t.name, res = t.res.name }; return View(m_sets.ToArray());
然后在视图中
@model IEnumerable @foreach (var item in Model) { @item.set ....