I am using WebAPI2 and i have 2 models
public class Model1
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public IList<Model2> Children{ get; set; }
}
public class Model2
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public int Model1Id { get; set; }
public virtual Model1 Model1 { get; set; }
}
In my view model i am convertinh this to ViewModel using Automapper My CRUD operations of first one is fine as ViewModel also same as Model1.
For my second model (Model2), the following is my ViewModel
public class Model2ViewModel
{
public int Id { get; internal set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public int Model1Id { get; set; }
public string Model1Name { get; internal set; }
public string Model1Description { get; internal set; }
}
My code like below;
public async Task<IHttpActionResult> Post(int model1Id, Model2ViewModel model)
{
try
{
model.Model1Id= model1Id;
var item = Mapper.Map<Model2>(model);
myRepo.Add(item);
myRepo.SaveAsync()
if (!result)
{
return BadRequest("Could not Save to the database");
}
return Created(uri, Mapper.Map<Model2ViewModel>(item));
}
catch (ArgumentException ex)
{
ModelState.AddModelError(ex.ParamName, ex.Message);
return BadRequest(ModelState);
}
}
I am using Repository Pattern and the logic in add record is below;
public void Add(T entity)
{
entity.RecordStatus = DataStatus.Active;
entity.CreatedDate = entity.UpdatedDate = DateTime.UtcNow;
_context.Set<T>().Add(entity);
}
public async Task<bool> SaveAsync()
{
int count = await _context.SaveChangesAsync();
return count > 0;
}
When i use post method of Model2 , i got error like Name is Required of Model1. Why Model1 also trying to create. Please help me
Note: For simplicity i added my repo calling, directly in the controller code. In real code it calling business method and from there only repo called.