c# - 我应该如何正确连接两个表,以便我可以访问其中一个实体中的属性?

标签 c# .net entity-framework linq asp.net-web-api

我正在使用 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/

相关文章:

.net - 如何在匹配表达式中使用 `&`?

c# - 为什么我的任务队列中的所有项目都被分配相同的值?

c# - 使用 System.Diagnostics.Process() 为进程设置图像名称和描述

.net - 使用 Autofac LifeTimeScope 和 Asp.net Core DI Extension IServiceScopeFactory 创建范围之间的区别

.net - 如果可以选择,混合模式程序集与单独的互操作 DLL 的优缺点是什么?

c# - 是否可以提取具有主类属性的对象?

c# - UpdateProgress 控件在 Safari 和 Chrome 上仍然可见

c# - 有没有办法单独设置 Winforms ListView 单元格的 BackColor?

c# - Entity Framework 中的意外行为

c# - 如何在数据库中存储两个相同的实体? Entity Framework ,C#