Rox*_*Pro -1 c# linq entity-framework entity-framework-6
我写了一个简单的查询(问题是当我尝试在Address下面设置时ProductCode):
var query = _connectDBContext.Products
.Join(_context.CustomerRelations,
Product => Product.ForeignKeyId,
CustomerRelation => CustomerRelation.CompanyId,
(Product, CustomerRelation) => new { Product, CustomerRelation })
.Select(x => new ProductDto
{
Title = x.Product.Title,
ProductCode = x.Product.Code,
Address = Map(x.Product.Addresses.OrderBy(x=> x.CreatedDate).FirstOrDefault()),
//Address = new AddressDTO // THIS WORKS BUT LOOKS UGLY :(
//{
// Address = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Address,
// Country = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Country,
// Zip = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Zip,
//},
})
.Where(x => x.Id == x.CustomerRelationId);
// Rest of the code
}
private AddressDTO Map(Address address)
{
return new AddressDTO
{
Address = address.Address,
Country = address.Country,
Zip = address.Zip,
};
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在这一行中断:
Address = Map(x.Product.Addresses.OrderBy(x=> x.CreatedDate).FirstOrDefault()),
Run Code Online (Sandbox Code Playgroud)
它说无法翻译 linq 并建议我重写查询..
但是这里注释的代码几乎可以完成相同的工作,所以如果我在Select 中删除调用Map方法,并且如果我在Select 中取消注释此代码,一切都会起作用,但我想摆脱这个 -为每个道具写太多,我想订购一次,然后我想使用它..但不幸的是我不知道如何..:OrderBy
//Address = new AddressDTO
//{
// Address = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Address,
// Country = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Country,
// Zip = x.Product.Addresses.OrderBy(x => x.CreatedDate).FirstOrDefault().Zip,
//},
Run Code Online (Sandbox Code Playgroud)
提前致谢,干杯
大概 Entity Framework 正在将此代码转换为 SQL,而Map()SQL 不知道您的自定义方法。幸运的是,该方法的作用不大,因此您应该能够将其功能直接移到查询中。
您可以使用.Select()将集合投影到新类型中(就像您已经为构建您的 所做的那样ProductDto)。
例如:
//...
Address = x.Product.Addresses.OrderBy(x=> x.CreatedDate)
.Select(x=> new AddressDTO
{
Address = x.Address,
Country = x.Country,
Zip = x.Zip
})
.FirstOrDefault()
//...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |