Reputation: 335
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);
}
Upvotes: 1
Views: 401
Reputation: 335
Finally I solved it like this:
public async Task <CategoryDTO> CreateCategory(CategoryDTO category)
{
Category myCategory = new Category()
{
CategoryName = category.CategoryName
};
await _context.Categories.AddAsync(myCategory);
await _context.SaveChangesAsync();//Save the changes
//pass CategoryId back with DTO
category.CategoryId = myCategory.CategoryId;
return category;
}
Upvotes: 1