代码之家  ›  专栏  ›  技术社区  ›  SK jha

将SQL查询转换为Entity Framework代码优先的方法

  •  0
  • SK jha  · 技术社区  · 4 年前

    我想先将SQL查询转换为Entity Framework代码,但无法实现。

    这是我的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记录。

    1 回复  |  直到 4 年前
        1
  •  0
  •   ESG    4 年前

    你的 Tests 模型似乎缺少导航属性 PatientTest 尽管如此,这仍然可以做到。

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

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