gpt4 book ai didi

c# - 组合来自多个表的数据以在 MVC View 中显示

转载 作者:行者123 更新时间:2023-11-30 20:21:51 26 4
gpt4 key购买 nike

我的 MVC 项目中有两个独立的模型

[Table("Table1")]   
public class Companies : IEnumerable
{
[Key]
public double ID { get; set; }
public System.Guid Key { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Industry { get; set; }
public string Rank{ get; set; }


public IEnumerator GetEnumerator()
{
yield return this.ID;
yield return this.Key;
yield return this.Name;
yield return this.Company;
yield return this.Industry;
yield return this.Rank;

}
}

[Table("Table2")]
public class Registration : IEnumerable
{
[Key]
public System.Guid Key { get; set; }
public string FieldValue{ get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }


public IEnumerator GetEnumerator()
{
yield return this.Key;
yield return this.FieldValue;
yield return this.StartDate;
yield return this.EndDate;

}
}

我需要在我的 View 中显示数据组合:

SELECT t2.FieldValue, t1.Name, t1.Company, t1.Industry, t1.Rank 
FROM Table1 as t1 INNER JOIN Table2 as t2 ON t1.Key=t2.Key

我创建了以下上下文类:

public class TablesContext: DbContext
{
public DbSet<Companies> companies { get; set; }
public DbSet<Registration> registration { get; set; }
}

现在我可以使用以下代码将公司的数据从 Controller 传递到 View :

private TablesContext tc = new TablesContext();
var comps = (from c in tc.companies
join r in tc.registry
on c.Key equals r.Key
select new { FieldValue=r.FieldValue, Name=c.Name, Company=c.Company,Industry=c.Industry, Rank=c.Rank});
return View(comps);

现在我有点卡住了,试图使 TablesContext 类可枚举并循环遍历 View 中的结果集。谁能指出我正确的方向?

最佳答案

在 ASP.NET MVC 中,您通常(可能)采用的方式是创建一个像这样的 ViewModel:

public class CompanyRegViewModel{
public string FieldValue {get;set;};
public string Name {get;set;};
public string Company {get;set;};
public string Industry {get;set;};
public string Rank {get;set;};
}

然后您可以像这样创建 CompanyRegViewModel 类的实例,而不是创建匿名对象:

var comps= ..... select new CompanyRegViewModel{ FieldValue=r.FieldValue, Name=c.Name....};

另一方面,您想要创建一个 View ,其模型是 CompanyRegViewModel 的列表。 (但不必是 List<>。它可以是实现 IEnumerable<> 的任何东西)。这是您可能的 View 的示例部分:

......
<table>
foreach(var item in Model){
<tr>
<td>item.Name</td>
<td>item.Company</td>
<td>item.Industry</td>
@*and so on*@
</tr>
}
</table>

关于c# - 组合来自多个表的数据以在 MVC View 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32976606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com