Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Read Related Data Using LINQ - one to many

$
0
0

I have these models,

public class PatReg
    {
        [NotMapped]
        private Int64 _FileId;
        [Key, Display(Name = "File Id"), ScaffoldColumn(false), DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Int64 FileId
        {
            get
            {
                return this._FileId;
            }
            set
            {
                this._FileId = value;
            }
        }
        [Required, Display(Name = "First Name")]
        public string FName { get; set; }

        public ICollection<PatPar> PatPar { get; set; }

    }


public class PatPar

    {
        [Key]
        public Int64 RecId { get; set; }
        [Display(Name = "Patient File Id"), Required]
        public Int64 FileId { set; get; }
        [Display(Name = "Partner File Id"), Required]
        public Int64 ParFileId { set; get; }
        [Display(Name = "Start Date"), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true), Required]
        public DateTime SDate { set; get; }
        [Display(Name = "End Date"), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime? EDate { set; get; }

    }

I m trying to get a JSON response that populates "ICollection<PatPar> PatPar" 

This is my API controller,

[HttpGet]
        public IEnumerable<PatReg> GetPatReg()
        {
            return _context.PatReg;
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetPatReg([FromRoute] long id)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var patReg = await _context.PatReg.SingleOrDefaultAsync(m => m.FileId == id);
            var parinfo = await _context.PatPar.SingleOrDefaultAsync(m => m.FileId == id); // I should select many records here
            if (patReg == null)
            {
                return NotFound();
            }

            var DataRes = new {
                sData = patReg
            };

            return Ok(DataRes);
        }

I know that I should use selectMany instead of using "SingleOrDefaultAsync" so I tried 

IEnumerable<PatPar> parinfo = await _context.PatPar.SelectMany(m => m.FileId == id);

but the compiler is giving me errors, what is the way to do it?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>