在linq查询中选择来自不同对象的数据

时间:2013-03-27 17:27:45

标签: c# asp.net linq

我还是LINQ的新手,我遇到了一些麻烦。我认为这一切都搞砸了,但我有一个包含几个属性的模型,以及一个不同类型的对象(Project)。我收到一个错误:无法将'AnonymousType#1'类型转换为'string'。我希望能够从我的NotificationModel对象中引用的ProjectModel对象中选择ProjectId和ProjectName。这就是我所拥有的,但这不起作用,我怎样才能改变它以正确地从ProjectModel对象中获取信息?

通知模型:

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

尝试检索数据:

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

2 个答案:

答案 0 :(得分:2)

如果Notification实体上的导航属性为Project,则可以执行以下操作:

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 :(得分: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
                            };