如何从包括使用LINQ另一个表到实体一个特定的行 [英] How to include one specific row from another table with LINQ to Entities

查看:94
本文介绍了如何从包括使用LINQ另一个表到实体一个特定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个表的数据库:客户 CustomerStatus CustomerStatus 是一个所谓的只读表。以客户的身份的所有更改导致表插入。当前的客户状态通过 CustomerStatus.StatusTimestamp 可定位。

I have a database with these two tables: Customer and CustomerStatus. CustomerStatus is a so called readonly table. All changes to a customer's status result in an INSERT into that table. The current customer status is locatable via CustomerStatus.StatusTimestamp.

现在我正在寻找一个LINQ到实体查询加载所有的客户提供其当前状态在一起。类似

Now I'm looking for a LINQ to entities query that loads all Customers together with their current status. Something like

.INCLUDE(CustomerStatus.OrderByDescending(StatusTimestamp).FirstOrDefault())

我还没有找到一个合适的方式与EF 4.0。

I haven't found a proper way with with EF 4.0.

我目前的解决方法是非常难看,并使用2个步骤:加载所有状态(在业务/数据层)的LINQ查询:

My current workaround is very ugly and uses 2 steps:

<

第1步code>
变种R =从C中db.Customers.Include(CustomerStatus)
选择C;

第2步:取(在MVC3视图在一个循环中)从GUI每个客户适当的状态:

step 2: take the suitable status from each customer in the GUI (in a loop in a MVC3 view):


c.CustomerStatus.OrderByDescending(I => i.StatusTimestamp).FirstOrDefault()

任何想法如何这可以直接在一个步骤中完成?

Any idea how this can be done directly in one step?

推荐答案

EF比你给它的信贷更加强大。的事情之一,它可以做的是工程复杂类型的内的的IQueryable 的(即,在一个数据库中命中)。这应该工作:

EF is more powerful than you give it credit for. One of the things it can do is project to complex types within an IQueryable (ie, in one database hit). This should work:

var data = 
    from c in db.Customers
    select new { 
        Customer = c, 
        LastStatus = c.CustomerStatus  // assuming navigation property set up right
                      .OrderByDescending(s => s.StatusTimestamp)
                      .FirstOrDefault()
    };

现在数据的IQueryable< anonymous_type> ,并且每个项目都有一个客户属性让消费者和 LastStatus 给予最新-时间戳的状态,或如果没有对于客户的任何状态记录。

Now data is an IQueryable<anonymous_type>, and each item has a Customer property giving the customer, and a LastStatus giving the latest-timestamped status, or null if there aren't any status records for the customer.

您可以在这里使用一个命名的类型也一样,它只是更快的让我输入这样说:。)

You can use a named type here too, it's just quicker for me to type it this way :).

这篇关于如何从包括使用LINQ另一个表到实体一个特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆