【问题标题】:Attributes of an entity not available in LINQ to Entities实体的属性在 LINQ to Entities 中不可用
【发布时间】:2011-11-29 20:15:54
【问题描述】:

这是我的简化示例的问题。

我有两个从 SQL Server 数据库建模的实体:

  1. 订单(可用列 = OrderID、PackageCount、ManufactureDate、ShipDate、StatusID)主键 = OrderID)
  2. OrderRecipients(可用列 = RecipientID、FirstName、LastName、Address、City、Zip、Country、OrderID;外键 = OrderID)

Orders 和 OrderRecipients 之间存在 [1 to many] 关系。一份订单可以有多个收件人。

我正在尝试通过以下代码提取订单的收件人。

  var allmyrecipients = from o in mycontext.Orders
                        where (o.SiteID.Equals("NYC") || o.SiteID.Equals("SFO"))
                        select o.OrderRecipients;

但是,当我尝试使用以下代码获取收件人姓名时:

 foreach (var recipient in allmyrecipients)
 {
   Console.WriteLine(recipient.FirstName);
 }

收件人的名字和其他属性在 Intellisense 下拉列表中不可用。我得到“不包含名字的定义”错误。

为什么会这样,补救措施是什么?我在这里做错了什么?我正在使用 VS 2010,Entity Framework 4。

感谢您抽出时间提供帮助。

【问题讨论】:

  • UPDATE1:我尝试了这段代码,它没有抛出错误:` foreach (var recipient in allmyrecipients) { foreach(var r in recipient) { Console.WriteLine(r.Name) ; } }` 为什么会这样?

标签: visual-studio-2010 entity-framework c#-4.0 linq-to-entities


【解决方案1】:

编辑:我将它重构为应该使用SelectMany 的东西。试一试:

var orders = from o in mycontext.Orders
    where (o.SiteID.Equals("NYC") || o.SiteID.Equals("SFO"))
    select o;

foreach (var recipient in orders.SelectMany(r => r.OrderRecipients)) 
{
    Console.WriteLine(recipient.FirstName); 
}

【讨论】:

  • 这样,我收到以下错误:Cannot implicitly convert type 'System.Linq.IQueryable<System.Data.Objects.DataClasses.EntityCollection<MyNamespace.OrderRecipient>>' to 'System.Linq.IQueryable<MyNamespace.OrderRecipient>'. An explicit conversion exists (are you missing a cast?)
  • 已更正和重构。我相信 SelectMany 应该正确处理投影。
  • 您的回复为我指明了正确的方向。 LINQ 查询实际上返回许多订单,每个订单都有许多收件人。这就是它抛出转换错误的原因。非常感谢。
猜你喜欢
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多