我有一个模型,其中包含六个类(由EF生成),我执行查询以将数据从数据库中获取到这些对象中。我需要在一个超类中使用多个类,因为我需要在一个视图中使用多个模型,顺便说一下,工作得很好。为简洁起见,我为其他类省略了很多查询。
然而,我遇到的问题是,一旦数据进入Controller,我如何根据某些业务逻辑进一步过滤数据?我不介意在中间层进行,如果这是最好的。
有两件事给我带来麻烦。
1)TimeTrackings类是Projects的子对象,由于设计时编译错误(如果我选择.Select到TimeTrackings的现有中间层查询),似乎无法过滤掉中间层上的任何内容
2)回到我的Controller之后,如果我想在我的结果集上进一步执行一些LINQ2Objects查询(从DB返回,它通常带有一个“var”变量。在WebForms中。我能够绑定对于网格,“var”变量。在MVC中,我需要能够将进一步过滤的数据放回“IEnumerable projects”变量中,以便能够将其传递给View。
我怎样才能完成这两件事?我真的很感激这方面的一些帮助,这将使我进一步澄清如何继续这种情况....
以下是我的代码:
生成的EF类:
namespace YeagerTechModel
{
using System;
using System.Collections.Generic;
public partial class Project
{
public Project()
{
this.TimeTrackings = new HashSet<TimeTracking>();
}
public short ProjectID { get; set; }
public string Description { get; set; }
public short CustomerID { get; set; }
public string Name { get; set; }
public short CategoryID { get; set; }
public short PriorityID { get; set; }
public short StatusID { get; set; }
public Nullable<decimal> Quote { get; set; }
public string Notes { get; set; }
public System.DateTime CreatedDate { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public virtual Category Category { get; set; }
public virtual Customer Customer { get; set; }
public virtual Priority Priority { get; set; }
public virtual Status Status { get; set; }
public virtual ICollection<TimeTracking> TimeTrackings { get; set; }
}
}
模型
namespace YeagerTechModel.ViewModels
{
public class ProjectStatus
{
public Project project { get; set; }
public Category category { get; set; }
public Customer customer { get; set; }
public Priority priority { get; set; }
public Status status {get;set;}
public TimeTracking tt {get; set;}
}
}
中间层方法(为简洁而省略了Try / Catch):
public IQueryable<Project> GetProjects()
{
using (YeagerTechEntities DbContext = new YeagerTechEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
IQueryable<Project> proj = DbContext.Projects.Include("TimeTrackings").Where(w => w.Notes != null && w.Status.Description != null);
}
}
控制器:
public ActionResult Index()
{
// Do all the LINQ2SQL query logic on the middle tier to get all the items in your collection.
IEnumerable<Project> projects = db.GetProjects();
// If we need to do more additional logic, we can do a LINQ2Objects query.
var tt = projects.Select(s=> s.TimeTrackings.Where(w=> w.Notes != null));
IEnumerable<Status> statuses = db.GetStatuses();
return View("ProjectStatus");
}
查看
@model YeagerTechModel.ViewModels.ProjectStatus
@{
ViewBag.Title = "ProjectStatus";
}
<h2>ProjectStatus</h2>
@using (Html.BeginForm("UpdateProjectStatus", "ProjectStatus", new AjaxOptions { HttpMethod = "POST" }))
{
@Html.EditorFor(x => x.project.Customer)
@Html.EditorFor(x => x.status.Description)
<input type="submit" value='Submit' />
}