我的MySQL数据库中有两个表autogen
public partial class adviser
{
public int adviserId { get; set; }
public string employeeNo { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public Nullable<int> statId { get; set; }
public Nullable<int> createdById { get; set; }
public Nullable<System.DateTime> createdOn { get; set; }
public virtual stat stat { get; set; }
public virtual user user { get; set; }
}
public partial class stat
{
public stat()
{
this.advisers = new HashSet<adviser>();
}
public int statId { get; set; }
public string statName { get; set; }
public string details { get; set; }
public virtual ICollection<adviser> advisers { get; set; }
}
然后我有这个方法来获取顾问的集合
public List<adviser> GetList(AdviserParam p)
{
List<adviser> items;
using (VotingContext context = new VotingContext())
{
items = context.advisers.Include("stat").Where(x =>
(x.adviserId == p.AdviserId || p.AdviserId == 0)
&& (x.employeeNo.Contains(p.EmployeeNo) || p.EmployeeNo == "")
&& (x.lastName.Contains(p.LastName) || p.LastName == "")
&& (x.firstName.Contains(p.FirstName) || p.FirstName == "")
&& (x.middleName.Contains(p.MiddleName) || p.MiddleName == "")
// && (x.statId == 1)
).ToList();
}
return items;
}
然后我使用这些代码将它们放入数据网格视图(获胜形式),我编辑了列,以便它不会显示adviserId和statId属性。
ItemsGridView.AutoGenerateColumns = false;
ItemsGridView.DataSource = vm.EntityList; // vm.EntityList is where I put the returned advisers from the GetList() method)
但是dgv不显示statName(来自stats表)。如何让它出现?
答案 0 :(得分:1)
要从 stat 对象中获取价值,您可以选择anonymous type并包含所有必需的属性。
我已经展示了一个包含statName和employeeNo的简单示例。
var items = context.advisers.Where(x => x.adviserId == yourAdviserID)
.Select(a=> new {name = a.stat.statName, employee=a.employeeNo}).ToList();
现在,如果您将项绑定到Datagridview,则只会看到名称和员工列。
如果您不想显示advisorID和statID,那么就不要将它们包含在新的匿名类型中。