Reputation: 25
I'm using an AddOrUpdate
method to update table entry.
I've tried this code:
_db.Cars.AddOrUpdate(car => car.Id == Id, new Car()
{
CarBrand = ViewModel.Brand,
CarModel = ViewModel.Model,
CarNumber = ViewModel.Number,
EngType = ViewModel.EngType
});
By using this I get an exception:
System.InvalidOperationException.
The properties expressioncar => Convert((car.Id == value(CarService.Windows.AddCarWindow).Car.Id))
is not valid. The expression should represent a property:t => t.MyProperty
. When specifying multiple properties use an anonymous type:t => new { t.MyProperty1, t.MyProperty2 }
.
I need help composing the expression.
Car class:
public class Car
{
public int Id { get; set; }
public string CarBrand { get; set; }
public string CarModel { get; set; }
public string CarNumber { get; set; }
public string EngType { get; set; }
}
Upvotes: 1
Views: 225
Reputation: 74595
If you know the Id of the car you wish to maybe update, just set it in the Car and let EF sort it out (EF [should, if configured it correctly] know the Id property is the key)
_db.Cars.AddOrUpdate(new Car()
{
Id = ID_YOU_WANT_TO_UPSERT,
CarBrand = ViewModel.Brand,
CarModel = ViewModel.Model,
CarNumber = ViewModel.Number,
EngType = ViewModel.EngType
});
EF will query the db for the Id you supply. If found, an update is applied. If not found, an insert is done. Note; if you do not specify every single property, any unspecified property is set to null on the db side, rather than ignored..
In terms of the error you're getting, the first argument to the overload you're using is not supposed to specify a predicate that identifies the object to update, it's supposed to list which properties shall be used in a predicate created by EF to determine equality. For example if you don't know the ID and CarNumber is unique you could add or update based on the CarNumber by:
_db.Cars.AddOrUpdate(car => car.CarNumber, new Car()
{
CarBrand = ViewModel.Brand,
CarModel = ViewModel.Model,
CarNumber = ViewModel.Number,
EngType = ViewModel.EngType
});
EF will look for an existing object based on the column you gave in the first argument car=>car.CarNumber
and the value you gave in the second argument (ViewModel.CarNumber
) - it will construct the WHERE CarNumber = 1234
from these
AddOrUpdate, AIUI, is no longer a thing - update can upsert in most common scenarios
Upvotes: 2