通过外键

时间:2016-11-10 17:22:22

标签: json entity-framework asp.net-web-api automapper-5

我正在使用SQL Server 2012,MVC WebAPI,AutoMapper和Entity Framework。 在数据库中,我有两个具有一对多关系的表,例如Categories和Products;一个类别可以有更多的产品,但一个产品只能有一个类别。我想要的是一个json,每个类别还包含Products.CategoryId字段的相关产品数组。

这是我在网上搜索后所做的:

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());
}

我的结果是带有和空或空产品数组的类别列表,我找不到解决方案。

我如何达到我的结果? 谢谢

修改

实体框架模型

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; }
}

类别和产品仅是示例,如果视图模型属性名称不相同,则忽略。

1 个答案:

答案 0 :(得分:1)

我怀疑你有Lazy Loading关闭。

所以一个解决方案是打开它,但我不建议它,因为它会执行许多数据库查询。

更好的选择是使用Eager Loading

return ViewModelMapper.Map<IEnumerable<CategoriesViewModel>>(
    Context.Categories.Include(c => c.Products));

return ViewModelMapper.Map<IEnumerable<CategoriesViewModel>>(
    Context.Categories.Include("Products"));

但AutoMapper的最佳选择是使用QueryableExtensions中的ProjectTo方法:

retirn Context.Categories.ProjectTo<CategoriesViewModel>();

由于链接中解释的原因。