I have a model class which looks like below-
public class ProductsViewModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool IsActive{ get; set; }
}
Also have below db Context
[Table("Products")]
public partial class Products
{
[Column("ProductId")]
public int ProductId { get; set; }
[Column("ProductName")]
public string ProductName{ get; set; }
[Column("IsActive")]
public bool IsActive { get; set; }
}
I am fetching the result using below LINQ query, which is returning correct data.
List<Products> productData = _context.Products.Where(x => x.IsActive == true).ToList();
Now, I want to bind this data i.e productData with my model.. something similat to ProductsViewModel = productData
.
I know I can loop through productData records and assign values to model properties but I am looking for a direct way to map these two. Is there any quick wat to get all the productData assigned to my model?
CodePudding user response:
You can use a mapping framework, the one I use the most is Automapper https://docs.automapper.org/en/stable/Getting-started.html.
public class AClass {
private readonly IMapper _mapper;
private readonly ADbContext _dbContext;
public AClass (IMapper mapper, ADBContext dbContext)
{
_mapper = mapper;
_dbContext = dbContext;
}
public async Task<IEnumerable<ProductViewModel>> AMethod()
{
var dbProducts = await _dbContext.Products.Where(x => x.IsActive == true).ToListAsync();
return dbProducts.Select(x => _mapper.Map<ProductViewModel>(x))
}
}
CodePudding user response:
You can use Automapper for a clean mapping as stated in another answer, alternatively, for more complex mapping, you can configure AutoMapper profiles for whatever exotic mappings you need.
For a direct assignment using =
it can be done by overloading the assignment operator in the ProductsViewModel
class:
public class ProductsViewModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool IsActive { get; set; }
public static implicit operator ProductsViewModel(Products obj)
{
return new ProductsViewModel()
{
ProductName = obj.ProductName,
IsActive = obj.IsActive,
ProductId = obj.ProductId,
};
}
}
Now your direct assignment will work fine.
For example:
var productsViewModels = _context.Products.Where(x => x.IsActive)
.Select(x => (ProductsViewModel)x).ToList();
Or more explicitly:
var productsViewModels = _context.Products.Where(p => p.IsActive)
.Select(x => { ProductsViewModel model = x; return model; }).ToList();
Here you have some running code you can consult for your convenience.