加入

时间:2017-10-20 12:16:32

标签: c# models datacontext

当我达成交易时,我正在尝试获取有关业务的详细信息。 我想翻译这个查询:

select d.*, b.* from deals d inner join business b
on b.id = d.businessId
where d.IsEvent = true

我试过这样:

public List<Deal> GetEventsDeals()
{
    var deals = DataContext.Deals.Join(DataContext.Businesses,
        d => d.BusinessId,
        b => b.Id,
        (d, b) => new {Business = b, Deal = d})
        .Where(d => (d.Deal.IsEvent == true));

    return deals.OrderBy(d => d.Deal.Order).Take(50).ToList();
}

但是我收到错误,我需要返回List<AnnoymousType>并且无法将其转换为List<Deal>

enter image description here

如何翻译我的查询?

1 个答案:

答案 0 :(得分:2)

错误消息告诉您正在尝试将匿名类型转换为Deals类型,但它不知道该怎么做。您需要这样做才能使代码生效

public List<Deal> GetEventsDeals()
{
    var deals = DataContext.Deals.Join(DataContext.Businesses,
        d => d.BusinessId,
        b => b.Id,
        (d, b) => new Deal(){Business = b, Deal = d})
        .Where(d => (d.Deal.IsEvent == true));

    return deals.OrderBy(d => d.Deal.Order).Take(50).ToList();
}

注意:正如Panagiotis Kanavos所指出的,这不是实体框架设计使用的方式。内连接应该用导航属性替换。

要做到这一点你应该有一个像这样的模型

public class Deal
{
    public int BusinessId { get; set; } 
    [ForeignKey("BusinessId")] // I believe this attribute is redundant because the names follow conventions, but you should check that
    public virtual Business Business { get; set; }
    public bool IsEvent {get;set;}
    public int Order {get;set;}
}

所以你按照以下方式打电话

var deals = DataContext.Deals.Include(d => d.Business).Where(d => d.Deal.IsEvent == true);

return deals.OrderBy(d => d.Deal.Order).Take(50).ToList();