Even though this is an old question and the answer(s) are technically correct, I would like to point out that certain decisions on how we architect our software solution do affect the way we approach and use ORM(s) such as EF.
As a result, they affect what we accept as the best answer, too.
In other words, why Christian's answer is not the accepted one?
In a layered architecture that follows basic DDD, the Product
class would probably be a domain model with methods to implement (any) business logic. In this case, the UnitPrice
property would be set or updated by such a method, say, CalculatePrice
instead of directly assigning a value to it:
public class Product
{
public int ProductID { get; private set; }
public decimal? UnitPrice { get; private set; }
...
public Product CalculatePrice(...)
{
UnitPrice = ...;
}
}
Having such a domain model, do you really need to ask which of its properties to update in the data store? Probably not. All you need is a reference to the tracked object to update. In the application layer the code becomes:
var product = repository.Find(productId);
if (product != null)
{
product.CalculatePrice(...);
repository.Update(product);
}
The implementation of the repository's Update
method is:
public Product Update(Product entity)
{
dbContext.Update(entity);
dbContext.SaveChanges();
return entity;
}
With regard to the OP, the above example showcases how design decisions affect both the meaning of our questions ("[...]best approach to update database") and which answer we mark as the accepted one.