json - Get related array from another table by foreign key -
i'm using sql server 2012, mvc webapi, automapper , entity framework. in database have 2 tables one-to-many relation, example categories , products; category can have more products product can have 1 category. want json each category contains array of related products products.categoryid field.
this made after search in internet:
public class categoriesviewmodel { public string categoryname { get; set; } public ienumerable<productsviewmodel> products { get; set; } } public class productsviewmodel { public string name { get; set; } } public static class viewmodelmapper { public static tdestination map<tdestination>(object source) { return mapper.map<tdestination>(source); } public static void registermaps() { automapper.mapper.initialize(config => { config.createmap<products, productsviewmodel>().reversemap(); config.createmap<categories, categoriesviewmodel>() .formember(dest => dest.products, opt => opt.mapfrom(src => src.products)) .reversemap(); } } } // repository public ienumerable<categoriesviewmodel> getcategories() { return viewmodelmapper.map<ienumerable<categoriesviewmodel>>(context.categories); } //business logic public ienumerable<categoriesviewmodel> getcategories() { return repository.getcategories(); } [route("categories"), httpget] public ihttpactionresult getcategories() { return ok(bl.getcategories()); }
my result list of categories , empty or null products array , cannot find solution.
how can reach result? thank you
edit:
entity framework models
public partial class category { [system.diagnostics.codeanalysis.suppressmessage("microsoft.usage", "ca2214:donotcalloverridablemethodsinconstructors")] public category() { this.products = new hashset<product>(); } public int categoryid { get; set; } public string categoryname { get; set; } [system.diagnostics.codeanalysis.suppressmessage("microsoft.usage", "ca2227:collectionpropertiesshouldbereadonly")] public virtual icollection<product> products { get; set; } } public partial class product { public int productid { get; set; } public int categoryid { get; set; } public string productname { get; set; } public virtual category category { get; set; } }
category , product examples, ignore if view model property names not same.
i suspect have lazy loading off.
so 1 solution turn on, not suggest it, because execute many database queries.
a better option use eager loading:
return viewmodelmapper.map<ienumerable<categoriesviewmodel>>( context.categories.include(c => c.products));
or
return viewmodelmapper.map<ienumerable<categoriesviewmodel>>( context.categories.include("products"));
but best option automapper use projectto
method queryableextensions
:
retirn context.categories.projectto<categoriesviewmodel>();
for reasons explained in link.
Comments
Post a Comment