Home > Net >  Bind DBContext Entity to Model on .Net Core
Bind DBContext Entity to Model on .Net Core

Time:09-14

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; }
}

And bellow the Entity:

    [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'm fetching the result using the 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 similar 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:

Is there any quick wat to get all the productData assigned to my model?

There are several. You can use Automapper as stated in another answer, alternatively, also using Automapper, and for more complex mapping, you can configure AutoMapper profiles for whatever exotic mappings you need.

For a direct assignment using =, like you exemplify in your question, and I reckon can be the simpler way for less complex entities, you can do it 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 you example, using Select and direct assingment (or cast which is also possible due to the operator overloading):

var productsViewModels = _context.Products.Where(x => x.IsActive)
    .Select(x => (ProductsViewModel)x).ToList();

Or explicit assignment:

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.

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))
      }
 }
  • Related