具有连接的数据上下文模型
Datacontext models with join
我想在达成交易时获取有关商家的详细信息。
我想翻译这个查询:
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();
}
但是我收到一个错误,我需要 return List<AnnoymousType>
并且无法将其转换为 List<Deal>
。
如何翻译我的查询?
错误消息告诉您您正在尝试将匿名类型转换为 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 所指出的,这不是 entityframework 设计使用的方式。内部联接应替换为导航属性。
要正确执行此操作,您应该有一个像这样的模型
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();
我想在达成交易时获取有关商家的详细信息。 我想翻译这个查询:
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();
}
但是我收到一个错误,我需要 return List<AnnoymousType>
并且无法将其转换为 List<Deal>
。
如何翻译我的查询?
错误消息告诉您您正在尝试将匿名类型转换为 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 所指出的,这不是 entityframework 设计使用的方式。内部联接应替换为导航属性。
要正确执行此操作,您应该有一个像这样的模型
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();