如何在将两个实体连接在一起后填充ViewModel对象

时间:2013-08-08 09:57:25

标签: asp.net-mvc linq entity-framework

我有以下viewModel类: -

public class RackJoin
    {
        public TMSRack Rack { get; set; }
        public Resource Resource { get; set; }
        public Technology Technology { get; set; }
        public ComponentDefinition ComponentDefinition { get; set; }
        public SDOrganization Site { get; set; }
        public SDOrganization Customer { get; set; }
    }

以下Uncompleted Repository模型方法用于连接两个实体: -

public IQueryable<TMSRack> AllFindRacks(string q)
        {
            List<RackJoin> rakjoin = new List<RackJoin>();
            var result = from rack in tms.TMSRacks
           .Include(rack => rack.DataCenter)
           .Include(rack => rack.Zone)
           .Include(rack => rack.TMSFirewalls)
           .Include(rack => rack.TMsRouters)
           .Include(rack => rack.TMSServers)
           .Include(rack => rack.TMSStorageDevices)
           .Include(rack => rack.TMSSwitches)
           .Include(rack => rack.Technology)
                         join resource in entities.Resources
                         .Include(a => a.ComponentDefinition)
                           .Include(a => a.ResourceLocation.SiteDefinition.SDOrganization)
                           .Include(a => a.ResourceLocation.SiteDefinition.AccountDefinition.SDOrganization)
                         on rack.Technology.IT360ID equals resource.RESOURCEID
                         where (q == null || rack.Technology.Tag.ToUpper().StartsWith(q.ToUpper()))
                         select //not sure what i should write here;

第一个问题;但我不确定如何在上述方法中根据联接结果填充List<RackJoin>

第二个问题;我从以下操作方法调用上述方法: -

 public ActionResult Index(string searchTerm = null, int page = 1)
            {
                var racks = repository.AllFindRacks(searchTerm).OrderBy(a => a.Technology.Tag).ToPagedList(page, 5);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_RackTable", racks);
                }
                return View(racks);
            }

我可以知道分页和连接如何协同工作,我的意思是EF会为满足where子句的所有记录进行连接,然后它会跳过并执行。以及将应用skip和take的实体?

1 个答案:

答案 0 :(得分:1)

第一个问题:

您可以访问select中的两个范围变量,因此您可以拥有一个包含机架和资源属性的视图模型。

select new RackJoin { 
         Rack = rack, 
         Resource = resource
     };

第二个问题:

只要返回IQueryable,EF就会看到Skip和Take运算符并将它们应用到SQL查询中,因此SQL Server负责连接和分页。

注意:您可以删除新的List代码行。

我在Standard LINQ Operators文章中有更多使用联接的示例。希望有所帮助。