【问题标题】:Need help on entity framework projections在实体框架预测方面需要帮助
【发布时间】:2015-01-29 13:05:33
【问题描述】:

我有两个实体:客户和地址

CUSTOMER
---------
Id
Name
Addresses

ADDRESS
---------
Id
CustomerId
Street
City
Country
IsPrimaryAddress

客户可以有多个地址,但只有一个主地址。 我只需要获取客户列表及其主要地址。如何通过一次调用数据库来获取它?

【问题讨论】:

标签: c# entity-framework entity-framework-6


【解决方案1】:

只需创建一个不是实体的新类型并从您的查询中返回它:

using (var db = new YourDbContext())
{
    var results = 
        from customer in db.Customers
        let primaryAddress = customer.Addresses.Single(a => a.IsPrimaryAddress)
        select new CustomerQueryResult
        {
            Id = customer.Id,
            Name = customer.Name,
            Address = primaryAddress
        };

    return results.ToArray();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2021-11-16
    • 1970-01-01
    • 2013-01-09
    • 2013-10-15
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多