如何修复无法隐式转换 System.Collections.Generic.List <RPHistory>
至System.Collections.Generic.List <RPHistory>
异常错误。
我正在尝试将两个实体组合在一起以获得单个列表
RP实体类:
public class RP
{
public int ID { get; set; }
public int RPID { get; set; }
public string Name { get; set; }
public int ProductID { get; set; }
}
RPHistory 实体类:
public class RPHistory:
{
public int ID { get; set; }
public int RPID { get; set; }
public string Name { get; set; }
public int ProductID { get; set; }
}
我创建了第三个类
RpWithHistory 类:
public class RpWithHistory {
public int ID;
public int RPID;
public string Name;
public int ProductID;
public List<RPHistory> History;
}
Linq 查询
var RPs = await Context.RP.Where(b => b.ProductID == request.ID)
.Select(x=> new RpWithHistory {
ID = x.ID,
RPID = x.RPID,
Name = x.Name,
ProductID = x.ProductID,
History = Context.RPHistory
.Where(y=> y.RPID
== x.RPID)
.ToList()
}
).ToListAsync();
但我收到此错误,
>Cannot implicitly convert System.Collections.Generic.List <RPHistory> to
>System.Collections.Generic.List <RPHistory> exception error
谢谢!
最佳答案
我不知道你为什么要这么做。我可以建议这个吗?
您不需要一路走来创建一个将两者结合起来的类。只需在 RP 上创建一个指向 RPHistory 对象的导航属性即可。
public class RP
{
public int ID { get; set; }
public int RPID { get; set; }
public string Name { get; set; }
public int ProductID { get; set; }
public ICollection<RPHistory> HistoryList { get; set; } // Navigation Property
}
public class RPHistory:
{
public int ID { get; set; }
public int RPID { get; set; }
public string Name { get; set; }
public int ProductID { get; set; }
[ForeignKey(nameof(RPID))] // Identify the Foreign Key from RP Class
public RP RP { get; set; } // Navigation back to RP
}
然后您可以使用 LINQ 将所有内容链接到一个列表中:
var RPs = Context.RP.Where(rp => rp.ProductID == request.ID)
.Include(rp=>rp.RPHistory) // This includes RPHistory
.ToList();
关于c# - 我该如何解决无法隐式将 Generic.List< > 转换为 Generic.List< >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61279809/