To add a new entity to your model, simply add it using <context>.<models>.Add(newEntity) and then call <context>.SaveChanges().

If you want to copy an existing entity and insert the copied item into the model, calling <context>.<models>.Add(copiedEntity) will add the entity to the model as a new entity, even if the Id is populated with an existing value.

using(MyDbContext context = new MyDbContext()) {
    MyModel myModel = context.FirstOrDefault(m => m.SomeProperty == someValue);
    myModel.SomeOtherProperty = someOtherValue; //user changed a value
    context.MyModels.Add(myModel); //add entity & autoincrement Id        
    database.SaveChanges();
}

Source: https://stackoverflow.com/a/25722197/4669143

Published On: March 8, 2019Categories: Entity Framework