我有两个有一对多关系的课程。我想根据父类的主键计算子类中的记录数。
父表类
public class SystemFamily
{
public SystemFamily()
{
DateCreated = DateTime.Now;
deleteFlag = false;
}
public int SystemFamilyID { get; set;}
public string FamilyName { get; set; }
public DateTime DateCreated { get; set; }
public string CreatedBy { get; set; }
public bool deleteFlag { get; set; }
public int SystemsCount {get;set;}
public virtual ICollection<Systems> Systems { get; set; }
public string SFamilyName
{
get
{
return FamilyName;
}
}
}
子表类
public class Systems
{
public int SystemsID { get; set; }
public string SystemName { get; set; }
public DateTime CreatedOn { get; set;}
public string CreatedBy { get; set; }
public int SystemFamilyID { get; set; }
public virtual SystemFamily SystemFamily { get; set; }
}
我不确定应该在哪里进行计数。在视图或控制器中?所以我会在建议之后发布所需的代码。
提前致谢! VINI
编辑1
public ActionResult Index()
{
//List<Systems> systems;
//var query = db.SystemFamily.Select(c => c.SystemFamilyID).ToList();
//foreach (var sid in query)
//{
// systems = db.Systems.Select(c => c.SystemFamilyID == sid).ToList();
//}
//int count = systems.Count();//Here you will get count
//ViewBag.Counts = count;
var viewmodel = new Sys_SysFam();
foreach (var item in db.SystemFamily)
{
int id = item.SystemFamilyID;
//SystemsCount
int count = db.Systems.Where(x => x.SystemFamilyID == id).Count();
item.SystemsCount = count;
}
ViewBag.Count = db.SystemFamily.Where(x=>x.deleteFlag==false).Count();
int count1 =db.Systems.Count();
ViewBag.SCount = count1;
return View(db.SystemFamily.Where(x=>x.deleteFlag==false).ToList());
}
这是我认为逻辑应该去的动作方法!我正在尝试使用foreach循环。但它不起作用它抛出异常:&#39; System.Data.Entity.Core.EntityCommandExecutionException&#39;
但我也有一个ViewSystem可以返回特定系列中的系统。
ViewSystem
public ActionResult ViewSystem(int? id)
{
var viewmodel = new Sys_SysFam();
ViewBag.SystemFamilyID = id;
if (id != null)
{
ViewBag.SystemFamilyID = id.Value;
var sysFamily = db.SystemFamily.Include(x => x.Systems).FirstOrDefault(x => x.SystemFamilyID == id.Value);
if (sysFamily != null)
{
viewmodel.Systems = sysFamily.Systems;
}
}
return View(viewmodel);
}
答案 0 :(得分:3)
你必须在Controller
中这样做public ActionResult ActionMethordNam()
{
List<Systems> systems;
var query = db.SystemFamily.Select(c=>c.SystemFamilyID).Tolist();
foreach(var sid in query)
{
systems = db.Systems.Select(c=>c.SystemFamilyID == sid).Tolist();
}
int count=systems.Count();//Here you will get count
Viewbag.Counts = count;
return View();
}
查看依据
中的计数 .cshtml中的 @Viewbag.Counts
@Html.TextBox("syscount", (string)ViewBag.Counts)
您可以通过传递作为参数将post方法中的值检索到post方法,现在您可以通过将此值分配给模型属性来将数据保存到表中
答案 1 :(得分:1)
var dataList = db.SystemFamily.Where(x => x.SystemFamilyID == id.Value).SelectMany(s => s.Systems).GroupBy(key => key.SystemFamilyID, sys => new {sys},
(i, sys) =>
new SystemsViewModel{
System = sys,
Count = sys.Count()
}).ToList();
将dataList传递给View