在我的 Web API 项目中,我有一个连接 2 个表(Table1 和 Table2)并返回 DTO 变量的查询:
int my_id=1;
var sample = db.Table1.Where(s1 => s1.Id == my_id)
.Join(db.Table2, s1 => s1.Id, s2 => s2.id_s1,
(s1, s2) => new sampleDTO()
{
User_Id = s1.User.Id,
ProdId = s2.ProdId
}));
现在我想加入 Table3,它与 Table1 结合并将参数添加到现有的“样本”变量。
我尝试在上面的代码后添加一个 Join 子句,但不起作用,因此我尝试使用 Table1 和 Table3 的 Join 子句创建一个新的 DTO 变量,然后合并这 2 个变量,但不起作用。
有什么想法吗?谢谢。
最佳答案
使用方法语法,您将必须投影一个新对象。但是,如果您切换到查询语法:
var result = from s1 in db.Table1
where s1.Id == my_id
join s2 in db.Table2 on s1.Id equals s2.id_s1
join s3 in db.Table3 on s2.SomeProperty equals s3.SomeProperty
select new sampleDTO
{
User_Id = s1.User.Id,
ProdId = s2.ProdId,
//PropertyFromTable3 = s3.SomePropertyFromTable3
};
如果您正在使用像 Entity Framework 这样的 ORM,请查看 navigation properties - 将省去所有连接在一起的麻烦
关于c# - 如何连接 table1 - table2 和 table1 - table3 并返回 DTO 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39916844/