I have 2 tables, one called Vm
and the other Datastore
, with a relation one-two-many between them. A Vm
can have only one Datastore
but a Datastore
can have severals Vm
s. I have my 2 classes and a basic post operation.
public class Datastore
{
// Primary Key
[Key]
public string DatastoreId { get; set; }
public string Name { get; set; }
}
public class Vm
{
// Primary Key
public int Id { get; set; }
public string Name { get; set; }
public int PowerState { get; set; }
public int NumCpu { get; set; }
public int MemoryGB { get; set; }
//Foreign Key
public string DatastoreId { get; set; }
//Navigation Property
public Datastore Datastore { get; set; }
}
// POST: api/Vms
[ResponseType(typeof(Vm))]
public async Task<IHttpActionResult> PostVm(Vm vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Vms.Add(vm);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = vm.Id }, vm);
}
The problem is that when I post a vm it looks like that it doesn't detect that the foreign exists. So it tries to create the foreignkey DatastoreId in the table Datastores where this primarykey already exists. Do I have to test if the key exists ? If so with do we configure one-two-many relation ?
When I test the post method in Postman with this it works only if DatastoreId exists
{
"DatastoreId": "datastore2",
"Name": "VM006",
"PowerState": 0,
"NumCpu": 2,
"MemoryGB": 4
}
But when I test the post method in Postman with this it will only works if the DatastoreId
doesn't exist yet
{
"Datastore": {
"DatastoreId": "datastore2",
"Name": "DAL"
},
"Name": "VM006",
"PowerState": 0,
"NumCpu": 2,
"MemoryGB": 4
}
Thank you for your replies!