2012-02-16 56 views
1

当我运行它(它说“无法确定属性名称”)时,出现InvalidOperationException异常。我检查了网络,但没有找到解决办法。它发生在foreach(联系人中的var c)行。使用Datacontext的InvalidOperationException

DataContext ctx = new DataContext("CrmConnection"); 

     var contacts = from c in ctx.contacts 
         where c != null 
         select new 
         { 
          acct = c.parentcustomerid == null ? "" : c.parentcustomerid.name, 
          last = c.lastname == null ? "" : c.lastname, 
          first = c.firstname == null ? "" : c.firstname 
         }; 

     List<string> lines = new List<string>(); 

     try 
     { 
      foreach (var c in contacts) *ex* 
      { 
       Console.WriteLine(c.acct); 
       Console.ReadLine(); 
       lines.Add(string.Format("{0}\t{1}\t{2}", c.acct, c.last, c.first)); 
       Console.WriteLine(c.acct); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(String.Format("Error: {0}", ex)); 
     } 

让我知道你是否有任何想法。谢谢。

+0

什么是* * * *? – devuxer 2012-02-16 00:29:10

+0

这是你正在得到的确切的错误信息,还是有更多的呢? – Matt 2012-02-16 03:02:32

+0

* ex *是我添加的,它是 – Paul 2012-02-16 14:38:25

回答

0

我怀疑c.parentcustomerid是一个id到一个相关的对象。它没有名称的属性,您正试图访问。

如果要获取父级客户的名称,您希望访问“parentcustomerid”指向的实际Customer对象。

如果你想要的是帐户ID(从ACCT财产猜测),那么只需要改变

acct = c.parentcustomerid == null ? "" : c.parentcustomerid.name 

acct = c.parentcustomerid == null ? "" : c.parentcustomerid 
+0

parentcustomerid不似乎是问题。当我用c.address1_city替换它(我知道过去曾用于datacontext)时,我得到了同样的错误。 – Paul 2012-02-16 21:25:53

+0

你可以发布你的数据库和/或你的映射代码的实际模式吗?正如Reza所提到的那样,这个异常是在foreach中发生的,因为在迭代它之前,查询不会被执行......实际问题出现在您的查询中(所以也许您的C#类到db的映射不正确) – Jaime 2012-02-16 21:34:36

0

发生在执行此异常的您查询,当接触迭代上下文尝试从sql执行您的查询。我觉得这个错误是因为你的上下文模型没有正确映射到你的数据库,可能是不同的表名或属性。

+0

I认为你可能是对的......这真的很奇怪,因为我使用了代码中用于不同函数的相同连接字符串('DataContext ctx = new DataContext(“CrmConnection”);'),而那个工作.. – Paul 2012-02-16 21:37:37

0
where c != null 

是问题所在。你检查什么字段为空c.parentcustomerid !=null?你不能对实体进行空检查。

另外,关闭Id的名称属性将在使用LINQ到Crm的查找上工作