我有一个具有多对多关系的两个实体的模型。我还需要存储有关连接的额外信息,因此我使用了自定义连接安排。该模型如下 -
疾病模型
public class Disease
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 DiseaseID { get; set; }
[Required]
[Display(Name = "Disease")]
[StringLength(100)]
public string DiseaseName { get; set; }
public virtual ICollection<App.Models.Medicine.MedicineToDisease> MedicineToDisease { get; set; }
}
医学模型
public class Medicine
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 MedicineID { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Generic Name")]
public string Medicine_Generic_Name { get; set; }
public virtual ICollection<App.Models.Medicine.MedicineToDisease> MedicineToDisease { get; set; }
加入表格
public class MedicineToDisease
{
public int MedicineToDiseaseId { get; set; }
public int MedicineId { get; set; }
public virtual Medicine Medicine { get; set; }
public int DiseaseId { get; set; }
public virtual Disease.Disease Disease { get; set; }
-- Other Information Fields related to the join --
}
我创建了一个列表视图模型,显示了所有药物的列表。我想显示上面连接表中有任何信息的所有疾病的 DISTINCT 列表。这是目前为止的ViewModel -
public class MedicineListViewModel
{
public Int32 MedicineID { get; set; }
public string MedicineName { get; set; }
public string AssociatedDiseases { get; set; }
}
查询信息的控制器代码如下 -
public ActionResult Index()
{
try
{
var model = db.Medicine.Select(u => new MedicineListViewModel
{
MedicineID = u.MedicineID,
MedicineName = u.Medicine_Generic_Name + " (" + u.Medicine_Trade_Name + ")",
NoOfTimesFree = u.Medicine_TimesFree,
AssociatedDiseases = db.MedicineToDisease.Where(m=>m.MedicineId == u.MedicineID).Select(s => s.Disease.DiseaseName).Distinct().ToList().ToString()
}).ToList();
return View(model);
}
catch (Exception ex)
{
TempData["ErrorMsg"] = ex.Message.ToString();
}
return null;
}
请建议。感谢。