【问题标题】:enntity frame work core two seperate data list from databse entity实体框架核心从数据库实体中分离出两个数据列表
【发布时间】:2018-04-24 15:16:41
【问题描述】:

我的控制器中有两个列表(.net core mvc 2.0,使用实体框架工作核心的数据库访问)

homeData.ListBrands = await _context.Brands.Where(b => formdata.UserCategories.Any(y => b.CategoryBrands.Any(c => c.CategoryID == y.CategoryID))).ToListAsync();
homeData.NewBrands = await _context.Brands.OrderByDescending(x => x.CreationDate).Take(5).ToListAsync();

两者都是数据库中的品牌列表 在品牌中,我有 colum 徽标,其中包含徽标名称,仅用于为客户端创建完整路径,我在路径中附加数据

 homeData.NewBrands.ForEach(x => x.BrandLogo = BrandLogo + "/" + x.BrandLogo);
 homeData.ListBrands.ForEach(x => x.BrandLogo = BrandLogo + "/" + x.BrandLogo);

如果同一品牌出现在两个列表中,则附加 url 将重复,因为它们代表相同的对象。

http://localhost:4399/Uploads/BrandLogo/http://localhost:4399/Uploads/BrandLogo/IMKbershkaD_19_Mar_2018_13_10_10.png

我已经尝试过新的内部选择

  homeData.NewBrands=_context.Brands.OrderByDescending(x => x.CreationDate).Select(x=>new Brand() {BrandCoverImages=x.BrandCoverImages,BrandDEscriptionAr=x.BrandDEscriptionAr,BrandDEscriptionEn=x.BrandDEscriptionEn,BrandID=x.BrandID,BrandLocations=x.BrandLocations,BrandLogo=x.BrandLogo }).Take(5).ToListAsync();

它对我有用,但我必须使用 new 甚至像brandCover 图像这样的内部对象,因为我还必须更改内部对象中的路径。从数据库中选择时是否有其他方法可以创建新对象。我正在使用实体核心 2.0 进行数据访问

【问题讨论】:

    标签: asp.net-core-mvc entity-framework-core


    【解决方案1】:

    您需要的是No-Tracking Query。不跟踪意味着 EF (1) 不会跟踪上下文中返回的实体实例,并且 (2) 不会重用上下文已经跟踪的实体实例。详情请见How Queries Work

    话虽如此,只需将AsNoTracking() 添加到查询根:

    homeData.ListBrands = await _context.Brands.AsNoTracking().Where(...
    homeData.NewBrands = await _context.Brands.AsNoTracking().OrderByDescending(...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多