I want to achieve the ADDorUpdate() method in Generic repository using EF Core like below? Can anyone help me?
public virtual void AddOrUpdate(T entity)
{
#region Argument Validation
if (entity == null)
{
throw new ArgumentNullException("entity");
}
#endregion
DbSet.AddOrUpdate(e => e.Id, entity);
this.DbContext.SaveChanges();
}
Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.
EF 6 is a stable and mature ORM while EF Core is relatively new. Microsoft rebuilt EF Core from the ground up and removed many of the internal dependencies and providers that EF 6 had (like SQLClient). In the long run, that will make EF Core much more extensible and lighter weight.
By default, EF Core creates a snapshot of every entity's property values when it is first tracked by a DbContext instance. The values stored in this snapshot are then compared against the current values of the entity in order to determine which property values have changed.
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
Simply use
context.Update(entity);
It does exactly AddOrUpdate
based on value of entity PrimaryKey (0 means Add, > 0 means Update):
public virtual void AddOrUpdate(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
this.DbContext.Update(entity);
this.DbContext.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With