Automapper - Create Object if src not null - asp.net-mvc

sHow can I do something like this:
.ForMember(dest => dest.Ad, opt => opt.MapFrom(src => src.Ask_Id == null ? null : new Ask { Id = src.Ask_Id }))
I get an unsupported mapping error.
Thanks.

I am not sure how your class object looks like, Pre-assuming that you have classes like below,
class Ask
{
public int Id { get; set; }
}
class DestinationDto
{
public Ask Ad { get; set; }
}
class SourceDto
{
public int? Ask_Id { get; set; }
}
If so, then use below mapper.
Mapper.CreateMap<SourceDto, DestinationDto>()
.ForMember(dest => dest.Ad, opt => opt.MapFrom(src => src.Ask_Id == null ? null : new Ask { Id = src.Ask_Id.Value }));
var source = new SourceDto { Ask_Id = 1}; // try with null
var destination = Mapper.Map<SourceDto, DestinationDto>(source);

Related

Changing the output DTO (return value) of the GetAll method in an AsyncCrudAppService

I'm using ABP's AsyncCrudAppService in my AppServices. Here's my interface:
public interface IAssetRequisitionAppService : IAsyncCrudAppService
<AssetRequisitionDto, Guid, GetAllInput, AssetRequisitionDto, AssetRequisitionDto, AssetRequisitionDetailsDto>
{ }
And the service:
public class AssetRequisitionAppService : AsyncCrudAppService
<AssetRequisition, AssetRequisitionDto, Guid, GetAllInput, AssetRequisitionDto, AssetRequisitionDto, AssetRequisitionDetailsDto>,
IAssetRequisitionAppService
{
public AssetRequisitionAppService(IRepository<AssetRequisition, Guid> repository) : base(repository)
{ }
}
Now, I believe all these standard CRUD methods will return the default type (which is AssetRequisitionDto in my case). But, what I want to do is to return a different type for Get() and GetAll() methods.
Get() should have a much more detailed DTO with subproperties of the Navigation props. But GetAll() should have a much less detailed one just to populate a table.
Is there a way to override the return types in some way?
Yes, there is some way.
// using Microsoft.AspNetCore.Mvc;
[ActionName(nameof(GetAll))]
public PagedResultRequestDto MyGetAll(PagedResultRequestDto input)
{
return input;
}
[NonAction]
public override Task<PagedResultDto<UserDto>> GetAll(PagedResultRequestDto input)
{
return base.GetAll(input);
}
Reference: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2859
Well I noticed I'll eventually need more complex filtering methods anyway. So, I created my custom types and methods.
First, I created my own GetAllInput derived from PagedAndSortedResultRequestDto. It's suited for most of my services, as I usually need to query the data related to employees and locations:
public class GetAllInput : PagedAndSortedResultRequestDto
{
public long? PersonId { get; set; }
public long? LocationId { get; set; }
public EEmployeeType? EmployeeType { get; set; }
}
After that I wrote a GetAll method for each of my services. They all return a PagedResultDto<> so I can use it's functionalities in presentation layer. Here's one example below:
//MovableAppService
public PagedResultDto<MovableLineDto> GetAllLinesRelatedToUser(GetAllInput input)
{
Logger.Info("Loading all movables related to current user");
IQueryable<Movable> queryable = null;
if (input.PersonId.HasValue)
{
if (input.EmployeeType == EEmployeeType.Recorder)
{
var recorder = _personRepository.GetAll()
.OfType<Employee>()
.FirstOrDefault(x => x.Id == input.PersonId);
var authorizedStorageIds = recorder.StoragesAuthorized.Select(y => y.Id);
queryable = _repository.GetAll()
.Where(x => authorizedStorageIds.Contains(x.StorageOfOriginId));
}
else if (input.EmployeeType == EEmployeeType.UnitManager)
{
var locationCodes = _locationRepository.GetAll()
.Where(x => x.ManagerInChargeId == input.PersonId)
.Select(x => x.Code);
foreach (var code in locationCodes)
{
queryable = _locationRepository.GetAll()
.Where(x => x.Code.StartsWith(code))
.SelectMany(x => x.AssignmentDocs)
.SelectMany(x => x.Movements)
.OfType<Assignment>()
.Where(x => x.TimeOfReturn == null)
.Select(x => x.Asset)
.OfType<Movable>();
queryable = queryable.Concat(queryable);
}
}
else if (input.TenantIdsOversee.Count() > 0)
{
var overseer = _personRepository.GetAll()
.OfType<Overseer>()
.FirstOrDefault(x => x.Id == input.PersonId);
var overseeingTenantIds = overseer.TenantsOversee.Select(y => y.Id);
queryable = _repository.GetAll()
.Where(x => overseeingTenantIds.Contains((int)x.TenantId));
}
else if (input.EmployeeType == EEmployeeType.Employee)
{
queryable = _personRepository.GetAll()
.OfType<Employee>()
.Where(x => x.Id == input.PersonId)
.SelectMany(x => x.AssignmentDocs)
.SelectMany(x => x.Movements)
.OfType<Assignment>()
.Where(x => x.TimeOfReturn == null)
.Select(x => x.Asset)
.OfType<Movable>();
}
}
var list = queryable.ToList()
.OrderBy(x => x.Category.Definition);
var items = _objectMapper.Map<IReadOnlyList<MovableLineDto>>(list);
return new PagedResultDto<MovableLineDto>(items.Count, items);
}
Btw, aaron's answer is probably valid for ASP.NET Core projects. But my project is in MVC EF6, so those annotations are not available for me.
Now I'm marking this as the answer but if there's a more elegant way, I'm happy to see and I'll change my mark then.

Viewmodel with conditional aggregation (Sums)

I have a viewmodel
public class RecTotal
{
public string PayType { get; set; }
public decimal TotalPrice { get; set; }
public string Category { get; set; }
}
public class ReconcileViewModel
{
public IEnumerable<RecTotal> RecTotals { get; set; }
public IEnumerable<RecInvoiceLineItem> LineItems { get; set; }
}
How do I create sums of the categories and create a new RecTotal record for each one. Ex:
ReconcileViewModel VM = new ReconcileViewModel();
foreach(POSItemCategory cat in db.POSItemCategories)
{
recLineItems.Where(p => p.Category == cat.ID).Sum(p => p.InvPrice);
}
The end result i'm looking for is something like
VM.RecTotal.Add(Sum(TotalPrice), foreach(Category)
I know I'm close but I just cant quite get it.
I found a way to do this, but it is "Ugly" in my opinion and there has to be a better way to do it....
var test = new List<RecTotal>();
foreach (POSItemCategory cat in db.POSItemCategories)
{
test.Add(new RecTotal
{
NumberOfItems = recLineItems.Where(p => p.Category == cat.ID).Count(),
TotalPrice = recLineItems.Where(p => p.Category == cat.ID).Sum(p => p.InvPrice),
PayType = "All",
Category = cat.Name,
NumberOfInvoices = recLineItems.Where(p => p.Category == cat.ID).Select(p => p.InvID).Distinct().Count()
});
};
VM.RecTotals = test;
Please let me know if there is a better way of doing this.
you can try this
var testdata = new List<RecTotal>();
testdata = recLineItems.Where(x => db.POSItemCategories.Select(a=>a.ID).Contains(x.Category))
.GroupBy(x => x.Category)
.Select(
x =>
new RecTotal()
{
Category = x.Key,
PayType = "All",
TotalPrice = x.Sum(z => z.InvPrice),
NumberOfItems = x.Count(),
NumberOfInvoices = x.Select(p => p.InvID).Distinct().Count()
}).ToList();

AutoMapper issue - Missing type map configuration or unsupported mapping

I followed a tutorial on repository and unit of work pattern design, it includes AutoMapper as well and I have absolutely no experience with it. The tutorial was with a older version and I had to modify the AutoMapperConfiguration class and their profiles a little bit, but now I get Missing type map configuration or unsupported mapping error.
public class Category
{
public int CategoryID { get; set; }
public string Name { get; set; }
public DateTime? DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
public virtual List<Gadget> Gadgets { get; set; }
public Category()
{
DateCreated = DateTime.Now;
}
}
public class Gadget
{
public int GadgetID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Image { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
public class Bootstrapper
{
public static void Run()
{
//Configure AutoMapper
AutoMapperConfiguration.Configure();
}
}
public static void Configure()
{
Mapper.Initialize(cfg => {
cfg.AddProfile<DomainToViewModelMappingProfile>();
cfg.AddProfile<ViewModelToDomainMappingProfile>();
});
//var config = new MapperConfiguration(cfg => {
// cfg.AddProfile<DomainToViewModelMappingProfile>();
// cfg.AddProfile<ViewModelToDomainMappingProfile>();
//});
//Mapper.Initialize(cfg =>
//{
// cfg.AddProfile<DomainToViewModelMappingProfile>();
// cfg.AddProfile<ViewModelToDomainMappingProfile>();
//});
}
public class ViewModelToDomainMappingProfile : Profile
{
public override string ProfileName
{
get { return "ViewModelToDomainMappings"; }
}
protected override void Configure()
{
//var config = new MapperConfiguration(cfg => cfg.CreateMap<GadgetFormViewModel, Gadget>());
//var mapper = new Mapper(config);
//Gadget dto = mapper.Map<Gadget>(GadgetFormViewModel);
//var config = new MapperConfiguration(cfg => {
// cfg.CreateMap<GadgetFormViewModel, Gadget>();
//});
//IMapper mapper = config.CreateMapper();
//var source = new GadgetFormViewModel();
//mapper.Map<GadgetFormViewModel, Gadget>(source);
//var gadgetFormViewModel = new GadgetFormViewModel();
//// Mapper.Configuration.CreateMapper
//Mapper.Map<GadgetFormViewModel, Gadget>(gadgetFormViewModel);
// //// .ForMember(g => g.Name, map => map.MapFrom(vm => vm.GadgetTitle))
// //.ForMember(g => g.Description, map => map.MapFrom(vm => vm.GadgetDescription))
// //.ForMember(g => g.Price, map => map.MapFrom(vm => vm.GadgetPrice))
// //.ForMember(g => g.Image, map => map.MapFrom(vm => vm.File.FileName))
// //.ForMember(g => g.CategoryID, map => map.MapFrom(vm => vm.GadgetCategory));
//Mapper.Map<GadgetFormViewModel, Gadget>(GadgetFormViewModel vm)
// .ForMember(g => g.Name, map => map.MapFrom(vm => vm.GadgetTitle))
// .ForMember(g => g.Description, map => map.MapFrom(vm => vm.GadgetDescription))
// .ForMember(g => g.Price, map => map.MapFrom(vm => vm.GadgetPrice))
// .ForMember(g => g.Image, map => map.MapFrom(vm => vm.File.FileName))
// .ForMember(g => g.CategoryID, map => map.MapFrom(vm => vm.GadgetCategory));
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<GadgetFormViewModel, Gadget>()
.ForMember(g => g.Name, map => map.MapFrom(vm => vm.GadgetTitle))
.ForMember(g => g.Description, map => map.MapFrom(vm => vm.GadgetDescription))
.ForMember(g => g.Price, map => map.MapFrom(vm => vm.GadgetPrice))
.ForMember(g => g.Image, map => map.MapFrom(vm => vm.File.FileName))
.ForMember(g => g.CategoryID, map => map.MapFrom(vm => vm.GadgetCategory));
});
IMapper mapper = config.CreateMapper();
var source = new GadgetFormViewModel();
var dest = mapper.Map<GadgetFormViewModel, Gadget>(source);
}
}
public class DomainToViewModelMappingProfile : Profile
{
public override string ProfileName
{
get { return "DomainToViewModelMappings"; }
}
protected override void Configure()
{
var configC = new MapperConfiguration(cfg => {
cfg.CreateMap<Category, CategoryViewModel>();
});
IMapper mapperC = configC.CreateMapper();
var sourceC = new Category();
mapperC.Map<Category, CategoryViewModel>(sourceC);
var configG = new MapperConfiguration(cfg => {
cfg.CreateMap<Gadget, GadgetViewModel>();
});
IMapper mapperG = configG.CreateMapper();
var sourceG = new Gadget();
mapperG.Map<Gadget, GadgetViewModel>(sourceG);
//Mapper.Initialize(x => { x.CreateMap<Category, CategoryViewModel>}());
//var category = new Category();
//var gadget = new Gadget();
//Mapper.Map<Category, CategoryViewModel>(category);
//Mapper.Map<Gadget, GadgetViewModel>(gadget);
}
}
public ActionResult Index(string category = null)
{
IEnumerable<GadgetViewModel> viewModelGadgets;
IEnumerable<Category> categories;
categories = categoryService.GetCategories(category).ToList();
viewModelGadgets = Mapper.Map<IEnumerable<Category>, IEnumerable<GadgetViewModel>>(categories);
return View(viewModelGadgets);
}
The error point at the viewModelGadgets = Mapper.Map<IEnumerable<Category>, IEnumerable<GadgetViewModel>>(categories); line inside the Index ActionMethod
Are you sure you want to map from a Category to a GadgetViewModel? You don't have a mapping defined for that combination. If it's valid, you need to add something like:
cfg.CreateMap<Category, GadgetFormViewModel>()
.ForMember(...)
);
If you're struggling with AutoMapper, consider writing your own mapping code. You'll have a clearer picture of what is going on.

Is my mocking for the EntitySet wrong?

I'm an experienced programmer, but new to LINQ/Moq/Ninject/MVC/MS Test/etc and have run into an issue I haven't been able to figure out.
I have built the SportsStore sample from the Pro ASP.NET MVC 2 Framework book (but with .NET 4.5/MVC 4). I got that working and now I've begun to convert it to work with our real database. The main difference at this point is that we do not only have a Product class, but also a ProductSub class. Each Product class consists of 1 or more ProductSub's and I have defined this with an EntitySet Association. To make the CartController to know which ProductSub to add to the Cart I decided to change CartController.AddToCart to take a productSubId instead of a productId.
Everything seems to work fine when I run the website and manually click "add product". However, when I run my unit tests I get a NullReferenceException because cart.Lines[0] is null. I don't think the error is in CartController since that seems to work when I run the webpage, and I tried to use the FakeProductsRepository (modified to add ProductSubID's) to rule out Moq causing this (which didn't help, so I don't think the error has anything to do with Moq).
I've figured out that this line in CartController returns null in the unit test but not when I run the webpage:
productsRepository.ProductSubs.FirstOrDefault(ps => ps.ProductSubID == productSubId);
So I tried to hard code the CartController to see if LINQ to the Product instead would work, which it did! I think that means that the productsRepository have Product's, but that for some reason the Product's doesn't have a ProductSub's. I'm I right so far?
My best guess is that there's something wrong with this code in the unit test:
new Product { ProductID = 2, ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 456} } }
But I can't figure out what. Is it wrong to use List? I tried using EntitySet instead but it made got the same error.
Unit test code:
[TestMethod]
public void Can_Add_Product_To_Cart()
{
// Arrange: Give a repository with some products...
var mockProductsRepository = UnitTestHelpers.MockProductsRepository(
new Product { ProductID = 1, ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 123 } } },
new Product { ProductID = 2, ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 456 } } }
);
var cartController = new CartController(mockProductsRepository, null);
var cart = new Cart();
// Act: When a user adds a product to their cart...
cartController.AddToCart(cart, 456, null);
// Assert: Then the product is in their cart
Assert.AreEqual(1, cart.Lines.Count);
Assert.AreEqual(456, cart.Lines[0].ProductSub.ProductSubID);
}
Cart class:
public class Cart
{
private List<CartLine> lines = new List<CartLine>();
public IList<CartLine> Lines { get { return lines.AsReadOnly(); } }
public void AddItem(ProductSub productSub, int quantity)
{
var line = lines.FirstOrDefault(x => x.ProductSub.ProductSubID == productSub.ProductSubID);
if (line == null)
lines.Add(new CartLine { ProductSub = productSub, Quantity = quantity });
else
line.Quantity += quantity;
}
public decimal ComputeTotalValue()
{
return lines.Sum(l => (decimal)l.ProductSub.Price * l.Quantity);
}
public void Clear()
{
lines.Clear();
}
public void RemoveLine(ProductSub productSub)
{
lines.RemoveAll(l => l.ProductSub.ProductSubID == productSub.ProductSubID);
}
}
public class CartLine
{
public ProductSub ProductSub { get; set; }
public int Quantity { get; set; }
}
Product class:
[Table]
public class Product
{
[HiddenInput(DisplayValue = false)]
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
[Column]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
[Column(Name = "info")]
public string Description { get; set; }
public float LowestPrice
{
get { return (from product in ProductSubs select product.Price).Min(); }
}
private EntitySet<ProductSub> _ProductSubs = new EntitySet<ProductSub>();
[System.Data.Linq.Mapping.Association(Storage = "_ProductSubs", OtherKey = "ProductID")]
public ICollection<ProductSub> ProductSubs
{
get { return _ProductSubs; }
set { _ProductSubs.Assign(value); }
}
[Required(ErrorMessage = "Please specify a category")]
[Column]
public string Category { get; set; }
}
[Table]
public class ProductSub
{
[HiddenInput(DisplayValue = false)]
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int ProductSubID { get; set; }
[Column(Name = "products_id")]
private int ProductID;
private EntityRef<Product> _Product = new EntityRef<Product>();
[System.Data.Linq.Mapping.Association(Storage = "_Product", ThisKey = "ProductID")]
public Product Product
{
get { return _Product.Entity; }
set { _Product.Entity = value; }
}
[Column]
public string Name { get; set; }
[Required]
[Range(0.00, double.MaxValue, ErrorMessage = "Please enter a positive price")]
[Column]
public float Price { get; set; }
}
UnitTestHelpers code (which should be fine since I tried the FakeProductsRepository):
public static IProductsRepository MockProductsRepository(params Product[] products)
{
var mockProductsRepos = new Mock<IProductsRepository>();
mockProductsRepos.Setup(x => x.Products).Returns(products.AsQueryable());
return mockProductsRepos.Object;
}
CartController code (which should be fine since it works on the webpage):
public RedirectToRouteResult AddToCart(Cart cart, int productSubId, string returnUrl)
{
//Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == 2);
//cart.AddItem(product.ProductSubs.FirstOrDefault(), 1);
ProductSub productSub = productsRepository.ProductSubs.FirstOrDefault(ps => ps.ProductSubID == productSubId);
cart.AddItem(productSub, 1);
return RedirectToAction("Index", new { returnUrl });
}
Code for FakeProductsRepository:
public class FakeProductsRepository : IProductsRepository
{
private static IQueryable<Product> fakeProducts = new List<Product> {
new Product { Name = "Football", ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 123, Price = 25 } } },
new Product { Name = "Surf board", ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 456, Price = 179 } } },
new Product { Name = "Running shoes", ProductSubs = new List<ProductSub> { new ProductSub { ProductSubID = 789, Price = 95 } } }
}.AsQueryable();
public FakeProductsRepository(params Product[] prods)
{
fakeProducts = new List<Product>(prods).AsQueryable();
}
public IQueryable<Product> Products
{
get { return fakeProducts; }
}
public IQueryable<ProductSub> ProductSubs
{
get { return fakeProducts.SelectMany(ps => ps.ProductSubs); }
}
public void SaveProduct(Product product)
{
throw new NotImplementedException();
}
public void DeleteProduct(Product product)
{
throw new NotImplementedException();
}
}
Please let me know if you need any other information.
Even though you have provided a lot of code some necessary information is missing so I'm assuming that IProductsRepository.ProductSubs returns IQueryable<ProductSub>. The MockProductsRepository method creates a mock for IProductsRepository but does not do any setup for IProductsRepository.ProductSubs. The mocking framework will most likely return an empty IQueryable<ProductSub>.
In the AddToCart you try to find the ProductSub using productsRepository.ProductSubs.FirstOrDefault. Because the mock returns an empty collection FirstOrDefault will return null thus you call cart.AddItem(null, 1) which explains why cart.Lines[0] is null.
Before fixing the mock you could consider doing parameter validation, e.g.
public void AddItem(ProductSub productSub, int quantity)
{
if (productSub == null)
throw new ArgumentNullException("productSub");
if (quantity < 1)
throw new ArgumentOutOfRangeException("quantity");
Then when you rerun your test it will be much clearer where your problem is.
Next thing will then be to create a setup for IProductsRepository.ProductSubs in MockProductsRepository:
mockProductsRepos
.Setup(x => x.ProductSubs)
.Returns(products.SelectMany(p => p.ProductSubs).AsQueryable());
This simply creates a collection of all the ProductSub objects from the Product objects provided to MockProductsRepository. You can of course modify this as you see fit.
I figured out the solution thanks to Martin Liversage. The mock WAS wrong, but I didn't figure it out because my FakeProductsRepository was ALSO wrong. Due to the dependency between Products and ProductSubs I don't think his suggested change to the mock would work though (but please correct me if I'm wrong).
The issue in FakeProductsRepository was that the constructor overwrote the initial fakeProducts collection with an empty collection. Once I changed that to only overwrite the initial collection if a new collection was supplied as parameter the unit tests worked using the FakeProductsRepository.
public FakeProductsRepository(params Product[] products)
{
if (products != null)
fakeProducts = new List<Product>(products).AsQueryable();
}
Thus there was an issue with the mock since that still didn't work. To solve it all I needed to do was to remove the ProductSubs function from IProductsRepository (which I had intended as a shortcut, but which I realized messed up the mocking). Once I did that and accessed the ProductSubs through the Products in CartController everything worked again.
public RedirectToRouteResult AddToCart(Cart cart, int productSubId, string returnUrl)
{
ProductSub productSub = productsRepository.Products.SelectMany(p => p.ProductSubs).FirstOrDefault(ps => ps.ProductSubID == productSubId);
cart.AddItem(productSub, 1);
return RedirectToAction("Index", new { returnUrl });
}
That was all I needed, but to simplify the test code I also decided to use pure ProductSub objects where that was enough instead of accessing them through a Product. Where I needed the whole Product (ie when the IProductsRepository was involved I used this code which I think is cleaner then creating the whole object on one line (ie with new List etc):
var ps1 = new ProductSub { ProductSubID = 11 };
var p1 = new Product();
p1.ProductSubs.Add(ps1);

Only parameterless constructors and initializers are supported in LINQ to Entities

There are several same questions that have same problem. But I cant find solution for me.
LinQ
var result = (from a in entity.TblAnalizorReadings
group a by new { date = new DateTime(((DateTime)a.okuma_tarihi).Year, ((DateTime)a.okuma_tarihi).Month, ((DateTime)a.okuma_tarihi).Day, ((DateTime)a.okuma_tarihi).Hour, 0, 0) } into g
select new AnalizorPivotChartModel
{
okuma_tarihi = g.Key.date,
Gerilim_Faz1 = g.Max(x => x.Gerilim_Faz1),
Gerilim_Faz2 = g.Max(x => x.Gerilim_Faz2),
Gerilim_Faz3 = g.Max(x => x.Gerilim_Faz3)
}).ToList();
Model
public class AnalizorPivotChartModel
{
public Nullable<System.DateTime> okuma_tarihi { get; set; }
public Nullable<decimal> Gerilim_Faz1 { get; set; }
public Nullable<decimal> Gerilim_Faz2 { get; set; }
public Nullable<decimal> Gerilim_Faz3 { get; set; }
}
I get error message as this question title. I can write more code if its neccesary.
Thanks.
var result = entity.TblAnalizorReadings
.GroupBy(a =>
new {
((DateTime)a.okuma_tarihi).Year,
((DateTime)a.okuma_tarihi).Month,
((DateTime)a.okuma_tarihi).Day,
((DateTime)a.okuma_tarihi).Hour
},
(k, g) => new {
okuma_tarihi = k,
Gerilim_Faz1 = g.Max(x => x.Gerilim_Faz1),
Gerilim_Faz2 = g.Max(x => x.Gerilim_Faz2),
Gerilim_Faz3 = g.Max(x => x.Gerilim_Faz3)
})
.AsEnumerable()
.Select(g => new AnalizorPivotChartModel
{
okuma_tarihi = new DateTime(okuma_tarihi.Year, okuma_tarihi.Month, okuma_tarihi.Day, okuma_tarihi.Hour, 0, 0),
Gerilim_Faz1 = g.Gerilim_Faz1,
Gerilim_Faz2 = g.Gerilim_Faz2,
Gerilim_Faz3 = g.Gerilim_Faz3
})
.ToList();

Resources