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

How to load Navigation Properties in a generic method

$
0
0

I would like to read data from a DB context and eagerly load the navigation properties.  My code successfully does this:

List<Peoplemvc> ap = await _context.People.Include(x => x.Links).ToListAsync();

The model I'm using is this

    [Table("peoplemvc")]
    public partial class Peoplemvc
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int PersonNumber { get; set; }
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Column(TypeName = "varchar(255)")]
        public string LastName { get; set; }
        [Column(TypeName = "varchar(255)")]

        public ICollection<Linksmvccore> Links{ get; set; }
    }

The navigation property references the following model

    [Table("linksmvccore")]
    public partial class Linksmvccore
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int LinkNumber { get; set; }
        [Column("BagID", TypeName = "int(11)")]
        public int? BagId { get; set; }
        [Column("PersonID", TypeName = "int(11)")]
        public int? PersonId { get; set; }

        public Bagsmvc Bag { get; set; }
        public Peoplemvc Person { get; set; }
    }

I currently have a generic method that reads tables successfully

public async Task<List<T1>> GetFromTable<T1>(DbSet<T1> TableToRead) where T1 : class
        {
            List<T1> results = new List<T1>();
            results = await TableToRead.ToListAsync() as List<T1>;
            return results;
         }

The question is how do I get this method to include / populate navigation properties if they exist in my model?  I imagine I'd use reflection but not sure how to implement it.  I am fine passing along an argument to the method with the navigation property like this, but don't know how to do it.

// I know this is not correct!
public async Task<List<T1>> GetFromTable<T1, T2>(DbSet<T1> TableToRead, Icollection<T2> nav) 
where T1 : class
where T2 : class
{
List<T1> results = new List<T1>();
results = await TableToRead.Include(x => x.nav).ToListAsync() as List<T1>;
return results;
}

Any help appreciated


Viewing all articles
Browse latest Browse all 9386

Trending Articles



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