C# 在linq查询中选择来自不同对象的数据
我对LINQ的事情还是个新手,有点麻烦。我认为这一切都搞砸了,但我有一个包含多个属性的模型,以及一个不同类型项目的对象。我收到一个错误:无法将类型“AnonymousType1”转换为“string”。我希望能够从我的NotificationModel对象中引用的ProjectModel对象中选择ProjectId和ProjectName。这是我所拥有的,但它不起作用,我如何更改它以正确地从ProjectModel对象获取信息 通知模式:C# 在linq查询中选择来自不同对象的数据,c#,asp.net,linq,C#,Asp.net,Linq,我对LINQ的事情还是个新手,有点麻烦。我认为这一切都搞砸了,但我有一个包含多个属性的模型,以及一个不同类型项目的对象。我收到一个错误:无法将类型“AnonymousType1”转换为“string”。我希望能够从我的NotificationModel对象中引用的ProjectModel对象中选择ProjectId和ProjectName。这是我所拥有的,但它不起作用,我如何更改它以正确地从ProjectModel对象获取信息 通知模式: public int id { get; set; }
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
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;
}
});
什么是不起作用的,你是得到了一个错误还是不是你所期望的?db.NotificationsLog与db.Projects有什么关系?是否确实要执行交叉联接?您使用的是LINQ to SQL还是LINQ to Entities实体框架?@p.s.w.g Notifications包含与项目相关的通知列表。如果没有加入,我还能用什么方法呢?projectId存储在Notification对象中,然后我需要提取项目信息以显示给它。@ios85 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;
}
});
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
};