post DTO to the table that is type of DbEntity in asp.net

Can anyone help me to post DTO to the table that is type of DbEntity?

in my context I have Categories table which is type of Category (DbEntity) :

public DbSet<Category> Categories {get;set;} 

in my service I want to post a new category to the Categories table but I want to use my DTO instead of my DbEntity:

 public async Task<CategoryDTO> CreateCategory(CategoryDTO category)
 {
     await _context.Categories.AddAsync(category).Select(c => new CategoryDTO
     {
         CategoryId = c.CategoryId, 
         CategoryName = c.CategoryName
                
     }).SaveChangesAsync();
          
     return category;         
 } 
  

I am getting error because Categories table is type of DbEntity and I want to add category that is type of CategoryDTO i.e data transfer object. I tried to translate my DbEntity to DTO using select but it did not work. can anyone help me to convert the types and properly add my new category to database?

this is also my controller:

        [HttpPost]
        public async Task<ActionResult> Post(CategoryDTO category)
        {
            if (category == null)
            {
                return NotFound();
            }

            if (!ModelState.IsValid) 
            {
                return BadRequest(ModelState); 
            }

            await _service.CreateCategory(category);
            return Ok(category);
        }


Read more here: https://stackoverflow.com/questions/64092120/post-dto-to-the-table-that-is-type-of-dbentity-in-asp-net

Content Attribution

This content was originally published by MJZ at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: