获取相关实体ID而不加载它

时间:2012-12-24 18:39:20

标签: entity-framework ef-code-first

我需要使用Entity Framework(代码优先)列出所有订单及其相应的客户ID。这可以在不查询Customers表的情况下实现,因为客户ID是Orders表中的FK。但是,EF也会针对Orders和Customers表生成选择。

这是实体模型和用于查询订单的代码:

public class Order
{
    public virtual Guid Id { get; set; }

    public virtual string Description { get; set; }

    public virtual Customer Customer { get; set; }
}

public class Customer
{
    public virtual Guid Id { get; set; }

    public virtual string Name { get; set; }
}

using (var context = new LazyLoadingEfContext())
{
    foreach (var order in context.Orders)
    {
        Console.WriteLine("Order {0}, Customer {1}", order.Description, order.Customer.Id);
    }
}

生成的SQL如下:

SELECT 
1 AS [C1], 
[Extent1].[Id] AS [Id], 
[Extent1].[Description] AS [Description], 
[Extent1].[Customer_Id] AS [Customer_Id]
FROM [dbo].[Orders] AS [Extent1]

exec sp_executesql N'SELECT 
[Extent2].[Id] AS [Id], 
[Extent2].[Name] AS [Name]
FROM  [dbo].[Orders] AS [Extent1]
INNER JOIN [dbo].[Customers] AS [Extent2] ON [Extent1].[Customer_Id] = [Extent2].[Id]
WHERE ([Extent1].[Customer_Id] IS NOT NULL) AND ([Extent1].[Id] =     
@EntityKeyValue1)',N'@EntityKeyValue1 uniqueidentifier',
@EntityKeyValue1='FF947EF3-5A3F-4A26-BDB9-039C49F559A7'

(加上参数@ EntityKeyValue1具有不同值的其他相同查询)

有没有办法配置EF以便从“父”对象中检索相关实体ID而不是加载相关实体?

BTW,我使用NHibernate测试了相同的场景,并且只对Orders表执行了一个查询:

SELECT this_.Id as Id1_0_, this_.Description as Descript2_1_0_, 
this_.Customer_id as Customer3_1_0_ FROM [Order] this_

1 个答案:

答案 0 :(得分:2)

试试这个:

public class Order
{
    public virtual Guid Id { get; set; }

    public virtual string Description { get; set; }

    public Guid CustomerID { get; set; }

    [ForeignKey("CustomerID ")]
    public virtual Customer Customer { get; set; }
}

之后,您应该能够在order.CustomerID循环中获得foreach,而无需查询Customers表。