从linq查询中的不同对象中选择数据

问题描述:

我还是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

,你可以这样做:

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; 
     } 
    }); 

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 
          };