2013-03-27 85 views
1

我還是LINQ的新手,並且遇到了一些麻煩。我認爲這一切都搞砸了,但我有一個模型,其中包含幾個屬性和不同類型的對象(項目)。我收到一個錯誤:無法將類型'AnonymousType#1'轉換爲'string'。我希望能夠從我的NotificationModel對象中引用的ProjectModel對象中選擇ProjectId和ProjectName。這就是我所擁有的,但這不起作用,我怎樣才能改變這個從ProjectModel對象正確地獲取信息?從linq查詢中的不同對象中選擇數據

通知型號:

public int id { get; set; } 
public int ProjectId { get; set; } 
public string ProjectName { get; set; } 
[StringLength(50)] 
public string CreatedBy { get; set; } 
public Nullable<System.DateTime> CreatedDateTime { get; set; } 
public Nullable<bool> IsDeleted { get; set; 

public virtual ProjectModel Project { get; set; } 

試圖檢索數據:如果你有你的Notification實體導航屬性Project

 var notifications = (from a in db.NotificationsLog 
          where a.CreatedBy == userID 
          orderby a.CreatedDateTime ascending 
          select new NotificationModel 
          { 
           id = a.id, 
           ProjectId = from p in db.Projects 
              select new 
                { 
                 ProjectId = p.ProjectId 
                } 
           ProjectName = from p in db.Projects 
              select new 

                { 
                 ProjectName = p.ProjectName 
                } 
           Notes = a.Notes; 
          }); 
+0

什麼是不工作,你得到一個錯誤或只是不是你所期望的? – BlackICE 2013-03-27 17:41:45

+0

db.NotificationsLog如何與db.Projects相關?你真的想做一個交叉連接嗎? – 2013-03-27 17:51:47

+0

你使用LINQ to SQL或LINQ to Entities(Entity Framework)嗎? – McCee 2013-03-27 17:51:55

回答

2

,你可以這樣做:

var notifications = 
    (from a in db.NotificationsLog 
    let p = a.Project 
    where a.CreatedBy == userID 
    orderby a.CreatedDateTime ascending 
    select new NotificationModel 
    { 
     id = a.id, 
     ProjectId = p.Id, 
     ProjectName = p.Name, 
     Project = new ProjectModel 
     { 
      ProjectId = p.Id 
      ProjectName = p.Name 
      Notes = a.Notes; 
     } 
    }); 
1
var notifications = from a in db.NotificationsLog 
        join p in db.Projects on a.ProjectId equals p.ProjectId 
        where a.CreatedBy == userID 
        select new NotificationModel 
          { 
           id = a.id, 
           ProjectId = p.ProjectId, 
           ProjectName = p.ProjectName, 
           Notes = a.Notes 
          };