Why my update command using EFCore is not updating the underlying data in the database though in middle-tier code it's successful, not throwing any error?
Let's try to get the root cause and how to solve this.
When creating the model class of related database object if the primary key name is Id then no need to explicitly mention the Key in ef-core OnModelCreating.
But if we've key name different from Id then we have to explicitly mention it in our OnModelCreating.
Something like this:
entity.HasKey(c => new {c.CustId });
Assume in the database we've Customers table like this:
CREATE TABLE [dbo].[Customers]( [CustId] [INT] IDENTITY(1,1) NOT NULL Primary Key, [FirstName] [VARCHAR](50) NULL )
Point to ponder: In the database table, column CustId is already defined as Primary key.
In EFCore model setup, it's up to us to configure the Key as (custId) or configure it as HasNoKey()
Assume we've set our entity with HasNoKey()
Customer-Model-HasNoKey protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { // Here we're not setting kay key to EFCore model. entity.HasNoKey(); entity.Property(e => e.FirstName) .HasMaxLength(50) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); }
And executed the command to update Customers entity using EFCore code
EfCore code snippet: var customer = _dbContext.Customers.Where(x => x.CustId == 1).FirstOrDefault(); customer.FirstName = "Updated name - with primary key"; _dbContext.SaveChanges();
Then trying to update the Customers entity from EFCore code base, related entries value in the database will not change. Here is the screen is shown before & after executing the ef-core code.
Now let's try to add the primary key in Customers model and then update
Customer-Model-HasKey protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { // define your key here. entity.HasKey(c => new {c.CustId }); entity.Property(e => e.FirstName) .HasMaxLength(50) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); }
and now execute the same EfCore code to update the customers' entity and verify in the database, yes, out data got updated.
Conclusion:
In EFCore if it good to have primary key explicitly defined (if it's not Id) in our model, otherwise at runtime we may come across a situation like this (update not happening, sorting not working....)
Comments
Post a Comment