I have 2 model classes which looks like this:
public class Collection
{
public int Id { get; set; }
public int CenterId { get; set; }
public string Reference { get; set; }
public Status Status { get; set; }
}
public class Status
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The statuses table is populated with 5 statuses. When I create a collection I would like to be able to attach the status to the collection. I have this BindingViewModel:
public class CollectionBindingModel
{
public int Id { get; set; }
[Required]
[Display(Name = "Center id")]
public int CenterId { get; set; }
public string Reference { get; set; }
public Status Status { get; set; }
}
When I call my controller, I would expect it to create the Collection with a foreign key pointing to the correct status. Instead it creates the status.... This is the code in the controller:
/// <summary>
/// Creates the collection
/// </summary>
/// <param name="model">The collection which is to be saved</param>
/// <returns>The collection that was saved to the database</returns>
[HttpPost]
[Route("")]
public IHttpActionResult Create(CollectionBindingModel model)
{
// Save our collection
return Save(model);
}
/// <summary>
/// Creates or updates the collection
/// </summary>
/// <param name="model">The collection which is to be saved</param>
/// <returns>The collection that was saved to the database</returns>
private IHttpActionResult Save(CollectionBindingModel model)
{
// If our ModelState is invalid, return a bad request
if (!ModelState.IsValid)
return BadRequest(ModelState);
// Assign our binding model to a new model
var collection = new Collection()
{
Id = model.Id,
CenterId = model.CenterId,
Reference = model.Reference,
Status = model.Status
};
// Save our collection
if (collection.Id == 0)
this.DbContext.Collections.Add(collection);
else
this.DbContext.Entry<Collection>(collection).State = EntityState.Modified;
// Save the changes
this.DbContext.SaveChanges();
// Get the location header
var locationHeader = new Uri(Url.Link("GetById", new { centerId = collection.CenterId, id = collection.Id }));
// Return the result
return Created(locationHeader, collection);
}
How can I get it to use the correct status that is already in the system?