C# EF Core LINQ 直接连接到模型

问题描述 投票:0回答:1
this.modelDataProductSubProductRate = this.contextSQL.ProductSubProductRate.Single(e => e.Id == this.parameter.Id.ToString());

我将 gridcontrol 数据源绑定到上面的上下文,它可以工作。

this.modelDataProductSubProductRate = this.contextSQL.ProductSubProductRate
.Join(this.contextSQL.LibraryCustomer,
pr => pr.Id, c => c.Id,
(pr, c) => new { pr })
.Single(e => e.pr.Id == this.parameter.Id.ToString());

但是当我需要更复杂的东西(例如加入)时,我收到了匿名类型的错误。有什么方法可以让它工作而不需要在代码中创建另一个类吗?如果需要的话,我已经有了带有虚拟列的模型,为什么我应该创建另一个类?

var query = this.contextSQL.ProductSubProductRate
.Join(this.contextSQL.LibraryCustomer,
pr => pr.Id, c => c.Id,
(pr, c) => new { pr })
.Single(e => e.pr.Id == this.parameter.Id.ToString());

我注意到如果我将查询放在 var 上,它可以工作,但是如何加载到数据上下文中?

FormattableString cmd = $@"SELECT spr.*, c.Name CustomerName FROM ProductSubProductRate spr 
LEFT JOIN LibraryCustomer c ON (c.Id = spr.IdCustomer)
WHERE (spr.IdSubProduct = {IdSubProduct})";
this.contextSQL.ProductSubProductRate.FromSql(cmd).ToList();

如果我使用我已经使用多年没有问题的.FromSQL,它的工作原理就像那样。但我想学习 LINQ 查询是否方法/语法,两者都不起作用。

c# entity-framework linq
1个回答
0
投票

请尝试如下所示,并且不要创建匿名对象。而不是使用

new { pr }
的匿名对象,只需返回
pr
。我在代码中所做的更改是替换

(pr, c) => new { pr }
(pr, c) => pr

.Single(e => e.pr.Id ==
.Single(e => e.Id ==

var query = this.contextSQL.ProductSubProductRate
            .Join(this.contextSQL.LibraryCustomer,
                pr => pr.Id, c => c.Id,
                (pr, c) => pr) 
            .Single(e => e.Id == this.parameter.Id.ToString());
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.