我有一个EF4实体工作组。以下是该模型的元数据供参考。
[MetadataType(typeof(WorkgroupMetaData))]
public partial class Workgroup {
public Contact manager { get; set; }
}
[Bind(Exclude = "id")]
public class WorkgroupMetaData
{
[ScaffoldColumn(false)]
public int id { get; set; }
[DisplayName("Org. Number")]
[Required(ErrorMessage = "Org. Number is required.")]
public string org_number { get; set; }
[DisplayName("Workgroup Name")]
[Required(ErrorMessage = "Workgroup name is required.")]
public string name { get; set; }
[DisplayName("Customer Contact")]
public int customer_contact_id { get; set; }
[DisplayName("Manager")]
public int manager_id { get; set; }
[DisplayName("Tech. Lead")]
public int lead_id { get; set; }
[DisplayName("Time Approver")]
public int time_approver { get; set; }
[DisplayName("Description")]
public string description { get; set; }
[ScaffoldColumn(false)]
public object created_at { get; set; }
[ScaffoldColumn(false)]
public object last_modified_at { get; set; }
}
我将ViewModel定义为:
public class WorkgroupViewModel
{
public Workgroup Workgroup { get; set; }
public List<Workgroup> Workgroups { get; set; }
}
在视图中,我有一个网格来转储可用的工作组。这有效,但我想知道如何将ID字段转换为另一个表中的实际字符串。基本上,经理,customer_contact,lead都是对Contact实体的引用。我想显示来自Contacts的姓名,而不仅仅是id。
如何实现这一目标?我看了一下,但似乎无法找到建议或答案。也许我从错误的角度来看这个?
答案 0 :(得分:1)
您可以考虑在Workgroup(装饰器模式)或Tuple周围使用包装器,或者创建一个将它们绑定在一起的自定义类。
public class WorkgroupDisplayModel
{
public Workgroup Workgroup { get; set; }
public Manager Manager { get; set; }
// Add additional properties for each related type
}
在您的EF查询中,您可以执行以下操作:
var query = from w in Context.Workgroups
join m in Context.Managers
on w.manager_id equals m.uid
// Additional joins for each related table
where w.Description == "Project 1" // Whatever criteria
select Tuple.Create(w, m); // Add param for each type
//or
//select new WorkgroupDisplayModel { Workgroup = w, Manager = m, ... };
var list = query.ToList();
var contact = list[0].Item1; // Tuple has strongly typed Item1 thru ItemN
var manager = list[0].Item2;
然后你的视图模型可能有:
List<Tuple<Workgroup, Manager, Customer, Lead>> Workgroups { get; set; }
或
List<WorkgroupDisplayModel> Workgroups { get; set; }