如何在没有ASP.NET 5 MVC模型的情况下从查询中访问数据

时间:2016-02-11 00:54:36

标签: c# asp.net asp.net-mvc entity-framework

我正在尝试使用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<MeasureTags> 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<MeasureTags> 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循环,它能够正确地提取每一行而不是列。错误:'对象'不包含'id'的定义(item.id)

<tbody>
@foreach (var item in Model)
{
   string tagid = "tag" + item.id;
       <tr>
        <td><input type="checkbox" checked id="@tagid"/></td>
        <td>@item.set</td>
        <td>@item.tag</td>
        <td>@item.res</td>
       </tr>
    }
}
</tbody>

我还为结果添加了一个额外的模型,但仍然没有成功。错误是'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();
    }
}

问题是:如果可能的话,如何在不需要其他模型的情况下访问“新的”通用对象属性?

1 个答案:

答案 0 :(得分:2)

您需要将查询投影到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<TagTable>
@foreach (var item in Model)
{
    <tr>
        <td>@item.set</td>
        ....