【问题标题】:Convert query from SQL to Entity Framework code first approach将查询从 SQL 转换为实体框架代码优先方法
【发布时间】:2020-03-28 02:15:22
【问题描述】:

我想先将我的 SQL 查询转换为实体框架代码,但无法做到。

这是我的 SQL 查询

select * from tests where id in(select testid from PatientTests where PatientId=@id)

这是这个模型中的测试模型,我想获取记录。

public class Tests
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Test Name")]
    public string TestName { get; set; }

    [Display(Name = "Short Name")]
    public string  ShortName { get; set; }

    [Display(Name="Technical Name")]
    public string  TechName { get; set; }

    [Required]
    [Display(Name ="Test Price")]
    public float TestPrice { get; set; }

    [Display(Name = "Sub Department")]
    public int SubDeptId { get; set; }

    [Display(Name = "Center")]
    public int CenterId { get; set; }

    public string Separate { get; set; }


    [Display(Name = "Sub Department")]
    [ForeignKey("SubDeptId")]
    //relation of departments table
    public virtual SubDepartments subDepartments { get; set; }

    [Display(Name = "Centers")]
    [ForeignKey("CenterId")]
    //relation of departments table
    public virtual Centers centers  { get; set; }

}

这是患者测试模型

 public class PatientTest
{
    [Key]
    public int Id { get; set; }

    [Display(Name ="Patient Id")]
    public int PatientId { get; set; }

    [Display(Name ="Test Id")]
    public int TestId { get; set; }

    [Display(Name ="Doctor")]
    public int DoctorId { get; set; }

    [Display(Name="Center")]
    public int CenterId { get; set; }


    [Display(Name = "Test")]
    [ForeignKey("TestId")]
    //relation of Tests table
    public virtual Tests Tests { get; set; }

    [Display(Name = "Doctor Reference")]
    [ForeignKey("DoctorId")]
    //relation of Doctors table
    public virtual Doctors Doctors { get; set; }

    [Display(Name = "Center Reference")]
    [ForeignKey("CenterId")]
    //relation of Centers table
    public virtual Centers Centers { get; set; }

    [Display(Name = "Patient")]
    [ForeignKey("PatientId")]
    //relation of Patient table
    public virtual Patient Patient { get; set; }

}

所以我想要测试表中的记录,其中 id 应该与 patientTest 表 testid 匹配,并且必须只获取给定的患者 ID 记录。

【问题讨论】:

  • 你能告诉我们你的模型是什么样的吗?

标签: sql-server entity-framework entity-framework-6 entity-framework-core


【解决方案1】:

您的Tests 模型似乎缺少PatientTest 的导航属性。不过还是可以的。

在这里猜测一下你的上下文属性是如何命名的。

var tests = context.PatientTests
                   .Where(pt => pt.PatientId == patientId)
                   .Select(pt => pt.Tests)
                   .ToList();

【讨论】:

  • Getting error here in Where(p => p.PatientId = id) 错误是“无法将 int 类型隐式转换为 bool”
  • 已编辑,应该是 == 而不是 =
  • 现在在 SelectMany() 参数空异常中出现异常
  • 尝试用 Select 替换它
  • 无法正常工作,出现错误不包含“测试”的定义
猜你喜欢
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多