我正在使用 EntityFramework 开发 Web API。 EntityFramework 是作为一个单独的项目构建的。在 API 中,我有以下模型:
namespace Web_API.Models
{
[Table("SomeFiles")]
public class SomeFilesViewModel
{
[Key]
public int FileId { get; set; }
public int PatchNumber{ get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
}
在 EF 中,我有以下实体:
namespace SomeDataAccess
{
public partial class Patch
{
public int PatchID { get; set; }
public double Number { get; set; }
}
public partial class PatchFile
{
public int FileID { get; set; }
public int PatchID{ get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
}
如何使用 LINQ 实现 GET 方法以返回两个 补丁
编号(不是补丁 ID)之间的文件列表?以下是我到目前为止所拥有的,但即使我加入了“数字”,也没有将其列为文件的属性。
public async Task<IHttpActionResult> GetSomeFileViewModels(double StartingPatch, double EndingPatch)
{
var files = from pf in _context.PatchFiles
join p in _context.Patches on pf.PatchID equals p.PatchID
select pf;
var patchFiles = await files.Where(i => i.Number(???) >= StartingPatch & i.Number <= EndingPatch)
.Select(someFiles => new SomeFileViewModel
{
FileId = files.FileID,
PatchNumber = (???),
Name = files.Name,
Type = files.Type,
}).ToListAsync();
return !patchFiles.Any()
? (IHttpActionResult)NotFound()
: Ok(patchFiles);
}
最佳答案
您需要修复您的Select
语句。目前您刚刚检索到 pf
,即 PatchFiles
。您可以像这样使用 select 语句选择匿名类型:
select new { PatchFile = pf, Patch = p};
你的查询现在应该是这样的:
var files = (from pf in _context.PatchFiles
join p in _context.Patches on pf.PatchID equals p.PatchID
select new { PatchFile = pf, Patch = p}).ToList();
然后你可以:
files.Where(i => i.Patche.Number)
关于c# - 我应该如何正确连接两个表,以便我可以访问其中一个实体中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159755/