1

我对 LINQ 还是很陌生,遇到了一些麻烦。我认为这一切都搞砸了,但我有一个模型,其中包含多个属性和不同类型的对象(项目)。我收到一个错误:无法将类型“AnonymousType#1”转换为“字符串”。我希望能够从我的 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;
                            });
4

2 回答 2

2

如果您的Notification实体上有导航属性 to 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;
         }
     });
于 2013-03-27T18:00:29.200 回答
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
                            };
于 2013-03-27T18:02:53.103 回答