c# - 具有连接的数据上下文模型

标签 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

如何翻译我的查询?

最佳答案

错误消息告诉您,您正在尝试将匿名类型转换为 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 所指出的,这不是 Entity Framework 设计的使用方式。内部联接应替换为导航属性。

要正确执行此操作,您应该有一个像这样的模型

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();

关于c# - 具有连接的数据上下文模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46848886/

相关文章:

c# - 如何使用 MVVM 从 DataGrid 传递有关所选项目的信息

c# - TimeSpan 的 Range 和 DisplayFormat 属性

c# - 设置 ExclusionNestedObjects 时,FluentAssertions 导致 ObjectDisposeException

c# - 如何为 .net core MVC Web 应用程序创建和显示 PDF 文件?

python - POST 保存后更新模型中的字段之一

ruby-on-rails - Rails has_many 与多个键关联

ruby-on-rails - Rails 将元素添加到一对多关联

c# - 将 ListView 与包含 UserControls 的 DataTemplates 绑定(bind)到 MVVM 中的 ViewModels

javascript - Polymer -> 类似于绑定(bind)中的 WPF/SL DataContext 的概念

c# - ViewModel 中的属性未显示在 View 中