2014-02-07 57 views
0

我想自己把下面的代码放在一个类,这样我可以重复使用它:查询使用一类具有LinqToSql

 var activePersons = (from p in _dataContextOrders.Persons 
          select new 
          { 
           p.ID, 
           p.WindowsUserID, 
           p.Name, 
           p.CommonShortName, 
           p.TeamID, 
           p.Telephone, 
           p.Fax, 
           p.Email, 
           p.FMSBudgetOfficerID, 
           p.Active 
          }).Where(p => p.Active).OrderBy(p => p.CommonShortName); 

所以我可以返回对象activePersons。我将这个替换这一切:

var activePersons = DataAccessLayer.ActivePersons.GetActivePersons(); 

但进一步下跌的一页,我有这样的:

var currentUser = activePersons.SingleOrDefault(p => p.WindowsUserID == strWindowsSessionUserId); 

这现在返回编译错误。有没有办法解决这个问题?

+1

你得到了什么错误? – Tigran

+1

您接受了[您先前的问题]的错误答案(http://stackoverflow.com/q/21630745/1159478)。如果你对这个问题使用了适当的答案,你就不会在这种情况下。 – Servy

回答

1

您收到错误的原因是因为您在查询中使用new关键字选择的匿名对象。你不能从你的方法返回匿名对象,所以我想你是返回object。现在对于你的方法调用者来说,它是一个object类型对象,它并不公开查询中选择的所有属性,(因为不知道类型,所以不能将它转换为类型)因此,错误。

需要创建一个新的类和所有的属性,并返回IEnumerable<yourClass>从该方法。

有一个way to return anonymous object mentioned by Jon Skeet但他不推荐它。

像定义一个类:

class ReturnedObject 
{ 
    public int ID { get; set; } 
    public string WindowsUserID { get; set; } 
    //..... rest of the properties 
} 

,然后在您的查询:

var activePersons = (from p in _dataContextOrders.Persons 
     select new ReturnedObject 
     { 
      ID = p.ID, 
      WindowsUserID = p.WindowsUserID, 
      //rest of the properties 

在你的方法指定的返回类型:

public IEnumerable<ReturnedObject> GetActivePersons(//parameters 
+0

谢谢你的帮助。我最终得到了这个工作。 DRY编程! –

+0

@SteveStaple,欢迎您的光临,但您在之前的问题中接受了[错误答案](http://stackoverflow.com/a/21631133/961113)以获得类似主题。 – Habib