1

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 Vms. 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!

rezurk
  • 11
  • 2

1 Answers1

0

You have to find the existence of the data store id before saving it.

Use following code to check the existence

Datastore= context.datastores.Single(c => c.datastoreid == @dataatoreid)          

ankur goel
  • 66
  • 5
  • Yep it works to test the existence of the DatastoreId, thank you. Now I have to complete my function to use existing DatastoreId if it exists or add new DatastoreId if not. But I still don't understand why it's not automatic. I mean, if we configure a one-to-many relation I thought that it would have automatically test the existence. – rezurk Apr 11 '18 at 06:30
  • By the way I found a interesting answer of @SteveWillcock who described the different function use to track existing or not item. On this post https://stackoverflow.com/a/3485370/9095242 – rezurk Apr 11 '18 at 06:38