0

我需要使用实体框架(代码优先)列出所有订单及其相应的客户 ID。由于客户 ID 是 Orders 表中的 FK,因此无需查询 Customers 表就应该可以做到这一点。但是,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 而不是加载相关实体?

顺便说一句,我已经使用 NHibernate 测试了相同的场景,并且只对 Orders 表执行了一个查询:

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

1 回答 1

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循环,而无需查询客户表。

于 2012-12-24T18:55:05.227 回答