【问题标题】:Get related array from another table by foreign key通过外键从另一个表中获取相关数组
【发布时间】:2016-11-11 03:52:14
【问题描述】:

我正在使用 SQL Server 2012、MVC WebAPI、AutoMapper 和实体框架。 在数据库中,我有两个具有一对多关系的表,例如类别和产品;一个类别可以有更多的产品,但一个产品只能有一个类别。我想要的是一个 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());
}

我的结果是包含空或 null Products 数组的类别列表,我找不到解决方案。

我怎样才能达到我的结果? 谢谢

编辑:

实体框架模型

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 只是示例,如果视图模型属性名称不同,请忽略。

【问题讨论】:

  • 我们可以看看模型吗?
  • 我认为对类名有误解。 CategoriesViewModel 的类是模型。我没有任何其他类型的代码: CategoriesRepository 通过 EF 从数据库获取数据并返回映射的 CategoriesViewModel。
  • 不,它们是 ViewModel,与问题无关。我需要实体模型,即Categories 和Products 类。
  • 你的意思是 EF 生成的类吗?我添加了它们。

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


【解决方案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>();

由于链接中解释的原因。

【讨论】:

  • 如果您提供一些反馈会很好,例如答案是否有助于解决问题等。
  • 当然,抱歉,我刚刚在工作中测试了它。它适用于实体框架的 AutoMapper 扩展的建议! ;) 在我的真实案例中,我也遇到了一些可空属性的映射问题,所以我修复了它们。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 2018-12-08
  • 2015-10-15
  • 2020-08-10
相关资源
最近更新 更多