Я получил ошибку automapper v8.0.1 в своем проекте asp.net MVC, которую я не могу устранить.Я хочу сопоставить DimProduct.cs с ProductDTO.cs, и после сопоставления я хочу проецировать из них определенные столбцы для своей сетки, а также включить EnglishProductSubcategoryName из ProductSubCategoryDTO.cs (еще один класс), который является свойством ProductDTO.cs.
Мой ProductService.cs имеет значение
public class ProductServices : IProductServices, IRequiresSessionState
{
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public ProductServices(UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IEnumerable<ProductDTO> Get(string product, string subCategory, string description, int? page = null, int? pageSize = null, string sortBy = null, bool isDescending = false)
{
var query = _unitOfWork.ProductRepository.IncludeMultiples(
c => (c.ProductSubcategoryKey == c.DimProductSubcategory.ProductSubcategoryKey),
includeProperties: prod => prod.DimProductSubcategory
).AsQueryable().Where(c => (c.ProductSubcategoryKey == c.DimProductSubcategory.ProductSubcategoryKey));
if (query != null)
{
if (!string.IsNullOrWhiteSpace(subCategory))
{
query = query.Where(q => q.DimProductSubcategory.EnglishProductSubcategoryName.Trim().ToLower() != null
&& q.DimProductSubcategory.EnglishProductSubcategoryName.Trim().ToLower().Contains(subCategory.Trim().ToLower())
&& q.DimProductSubcategory.ProductSubcategoryKey == q.ProductSubcategoryKey
);
}
if (!string.IsNullOrWhiteSpace(product))
{
query = query.Where(q => q.EnglishProductName.Trim().ToLower().Contains(product.Trim().ToLower()));
}
if (!string.IsNullOrWhiteSpace(description))
{
query = query.Where(q => q.EnglishDescription.Trim().ToLower().Contains(description.Trim().ToLower()));
}
if (System.Web.HttpContext.Current == null)
{
HttpContext.Current.Session["query"] = query;
HttpContext.Current.Session["total"] = query.Count();
}
var products = _unitOfWork.ProductRepository.SortPagination(query.AsQueryable(), sortBy, isDescending, page, pageSize).AsQueryable().Select(x => x);
if (products.Any())
{
var pp = products.ToList().Select(Mapper.Map<DimProduct, ProductDTO>);
// var pp = Mapper.Map<IEnumerable<DimProduct>, IEnumerable<ProductDTO>>(products);
return (IEnumerable<ProductDTO>)pp.Select(u => new
{
u.ProductKey,
u.EnglishProductName,
u.EnglishDescription,
u.ProductSubcategoryKey,
u.ProductSubCategory.EnglishProductSubcategoryName,
u.WeightUnitMeasureCode,
u.SizeUnitMeasureCode,
u.StandardCost,
u.FinishedGoodsFlag,
u.Color,
u.SafetyStockLevel,
u.ReorderPoint,
u.ListPrice,
u.Size,
u.SizeRange,
u.Weight,
u.DaysToManufacture,
u.ProductLine,
u.DealerPrice,
u.Class,
u.Style,
u.ModelName,
u.StartDate,
u.EndDate,
u.Status
}).ToList();
}
}
return Enumerable.Empty<ProductDTO>();
}
}
Ошибка:
{"Типы сопоставления ошибок. \ R \ n \ r \ n Типы сопоставления: \ r \ nDimProduct_258DE10A937C4F7D708A72334D5BDC7D420B6AFeFeFeEEEEEEEEE-ENDFeeee.dll\ г \ nSystem.Data.Entity.DynamicProxies.DimProduct_258DE10A937C4F7D708A72334D5BDC7D420B08BA63CEEE9B6F95FA7E90A349EA -> ReportingSystem.ReportingSystemDTO.ProductDTO \ г \ п \ г \ nType конфигурации Карта: \ г \ nDimProduct_258DE10A937C4F7D708A72334D5BDC7D420B08BA63CEEE9B6F95FA7E90A349EA -> ProductDTO \ г \ nSystem.Data.Entity.DynamicProxies.DimProduct_258DE10A937C4F7D708A72334D5BDC7D420B08BA63CEEE9B6F95FA7E90A349EA -> ReportingSystem.ReportingSystemDTO.ProductDTO \ r \ n \ r \ nПункт назначения: \ r \ nDimProductSubcategory \ r \ n "}
Я хочу получитьи эти столбцы
- u.EnglishProductName
- u.EnglishDescription
- u.ProductSubcategoryKey
- u.ProductSubCategory.EnglishProductSubcategoryName
- u.SizeUnitMeasureCode
- u.StandardCost
- u.FinishedGoodsFlag
- u.Color
- u.SaSStockS*
- u.ReorderPoint
- u.ListPrice
- u.Size
- u.SizeRange
- u.Weight
- u.DaysToManufacture
- u.ProductLine
- u.DealerPrice
- u.Class
- u.Style
- u.ModelName
- u.StartDate
- u.EndDate
- u.Status
Структура моего проекта выглядит следующим образом:
У меня есть DimProduct.cs, который является классом сущностного каркаса и классом DTO ProductDTO.cs.
using AutoMapper;
using Resolver;
using System.ComponentModel.Composition;
using ReportingSystem.ReportingSystemDTO;
using ReportingSystemDataModels.EntityModel;
using ReportingSystemServices.Extensions;
using System.Collections.Generic;
namespace ReportingSystem.Services
{
[Export(typeof(IComponent))]
public class DependencyResolver : IComponent
{
public void SetUp(IRegisterComponent registerComponent)
{
registerComponent.RegisterType<IProductServices, ProductServices>();
}
}
public class MappingProfile : Profile
{
public static void Initialize()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<DimProduct, ProductDTO>();
cfg.CreateMap<ProductDTO, DimProduct>();
cfg.CreateMap<DimProductSubcategory, ProductSubCategoryDTO>();
cfg.CreateMap<ProductSubCategoryDTO, DimProductSubcategory>();
cfg.CreateMap<ProductCategoryDTO, DimProductCategory>();
cfg.CreateMap<DimProductCategory, ProductCategoryDTO>();
cfg.CreateMap<FactInternetSale, FactInternetSalesDTO>();
cfg.CreateMap<FactInternetSalesDTO, FactInternetSale>();
cfg.CreateMap<FactProductInventory, FactProductInventoryDTO>();
cfg.CreateMap<FactProductInventoryDTO, FactProductInventory>();
cfg.CreateMap<FactResellerSale, FactResellerSaleDTO>();
cfg.CreateMap<FactResellerSaleDTO, FactResellerSale>();
});
}
}
}
Я рассмотрел похожую схему ошибокдля авто картографа разных версий.Они не работали.
DimProduct.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ReportingSystemDataModels.EntityModel
{
using System;
using System.Collections.Generic;
public partial class DimProduct
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DimProduct()
{
this.FactInternetSales = new HashSet<FactInternetSale>();
this.FactProductInventories = new HashSet<FactProductInventory>();
this.FactResellerSales = new HashSet<FactResellerSale>();
}
public int ProductKey { get; set; }
public string ProductAlternateKey { get; set; }
public Nullable<int> ProductSubcategoryKey { get; set; }
public string WeightUnitMeasureCode { get; set; }
public string SizeUnitMeasureCode { get; set; }
public string EnglishProductName { get; set; }
public string SpanishProductName { get; set; }
public string FrenchProductName { get; set; }
public Nullable<decimal> StandardCost { get; set; }
public bool FinishedGoodsFlag { get; set; }
public string Color { get; set; }
public Nullable<short> SafetyStockLevel { get; set; }
public Nullable<short> ReorderPoint { get; set; }
public Nullable<decimal> ListPrice { get; set; }
public string Size { get; set; }
public string SizeRange { get; set; }
public Nullable<double> Weight { get; set; }
public Nullable<int> DaysToManufacture { get; set; }
public string ProductLine { get; set; }
public Nullable<decimal> DealerPrice { get; set; }
public string Class { get; set; }
public string Style { get; set; }
public string ModelName { get; set; }
public byte[] LargePhoto { get; set; }
public string EnglishDescription { get; set; }
public string FrenchDescription { get; set; }
public string ChineseDescription { get; set; }
public string ArabicDescription { get; set; }
public string HebrewDescription { get; set; }
public string ThaiDescription { get; set; }
public string GermanDescription { get; set; }
public string JapaneseDescription { get; set; }
public string TurkishDescription { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public string Status { get; set; }
public virtual DimProductSubcategory DimProductSubcategory { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FactInternetSale> FactInternetSales { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FactProductInventory> FactProductInventories { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FactResellerSale> FactResellerSales { get; set; }
}
}
ProductDTO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportingSystemDataModels.EntityModel;
using AutoMapper;
namespace ReportingSystem.ReportingSystemDTO
{
public class ProductDTO
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ProductDTO()
{
this.FactInternetSales = new HashSet<FactInternetSaleDTO>();
this.FactProductInventories = new HashSet<FactProductInventoryDTO>();
this.FactResellerSales = new HashSet<FactResellerSaleDTO>();
// this.ProductSubCategory = new HashSet<ProductSubCategoryDTO>();
}
public int ProductKey { get; set; }
public string ProductAlternateKey { get; set; }
public Nullable<int> ProductSubcategoryKey { get; set; }
public string WeightUnitMeasureCode { get; set; }
public string SizeUnitMeasureCode { get; set; }
public string EnglishProductName { get; set; }
public string SpanishProductName { get; set; }
public string FrenchProductName { get; set; }
public Nullable<decimal> StandardCost { get; set; }
public bool FinishedGoodsFlag { get; set; }
public string Color { get; set; }
public Nullable<short> SafetyStockLevel { get; set; }
public Nullable<short> ReorderPoint { get; set; }
public Nullable<decimal> ListPrice { get; set; }
public string Size { get; set; }
public string SizeRange { get; set; }
public Nullable<double> Weight { get; set; }
public Nullable<int> DaysToManufacture { get; set; }
public string ProductLine { get; set; }
public Nullable<decimal> DealerPrice { get; set; }
public string Class { get; set; }
public string Style { get; set; }
public string ModelName { get; set; }
public byte[] LargePhoto { get; set; }
public string EnglishDescription { get; set; }
public string FrenchDescription { get; set; }
public string ChineseDescription { get; set; }
public string ArabicDescription { get; set; }
public string HebrewDescription { get; set; }
public string ThaiDescription { get; set; }
public string GermanDescription { get; set; }
public string JapaneseDescription { get; set; }
public string TurkishDescription { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public string Status { get; set; }
// //aded
public string EnglishProductSubCategoryName { get; set; }
//
// //added ends
}
}
И мой файл Global.asax имеет
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using AutoMapper;
using Newtonsoft.Json;
using ReportingSystem.Services;
namespace RepotingSystem
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Define Formatters
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
var appXmlType = formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
//Add CORS Handler
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
GlobalConfiguration.Configuration.EnsureInitialized();
//Configure Automapper
AutoMapperConfiguration.Configure();
}
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(c => c.AddProfile<MappingProfile>());
Mapper.Configuration.AssertConfigurationIsValid();
}
}
}
}
DimProductSubcategory.cs (EntityClass)
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ReportingSystemDataModels.EntityModel
{
using System;
using System.Collections.Generic;
public partial class DimProductSubcategory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DimProductSubcategory()
{
this.DimProducts = new HashSet<DimProduct>();
}
public int ProductSubcategoryKey { get; set; }
public Nullable<int> ProductSubcategoryAlternateKey { get; set; }
public string EnglishProductSubcategoryName { get; set; }
public string SpanishProductSubcategoryName { get; set; }
public string FrenchProductSubcategoryName { get; set; }
public Nullable<int> ProductCategoryKey { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<DimProduct> DimProducts { get; set; }
public virtual DimProductCategory DimProductCategory { get; set; }
}
}
ProductSubcategoryDTO.cs (класс DTO)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ReportingSystem.ReportingSystemDTO
{
public class ProductSubCategoryDTO
{
public int ProductSubcategoryKey { get; set; }
public Nullable<int> ProductSubcategoryAlternateKey { get; set; }
public string EnglishProductSubcategoryName { get; set; }
public string SpanishProductSubcategoryName { get; set; }
public string FrenchProductSubcategoryName { get; set; }
public Nullable<int> ProductCategoryKey { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ProductDTO> Products { get; set; }
public virtual ProductCategoryDTO ProductCategory { get; set; }
}
}