Working of HasComputedColumnSql() method in EF Core

net 6 newbie 121 Reputation points
2024-03-09T09:52:48.4266667+00:00

I have configured the updatedAt property as shown below. I expected that the updatedAt value of the corresponding row alone will change when inserting or updating. But when tried this it is updating entire column i.e all the rows of the UpdatedAt are getting changed which is not expected.

Am I doing any wrong configuration or it is the expected behavior. Please correct the working

modelbuilder
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
724 questions
Entity Framework Core Training
Entity Framework Core Training
Entity Framework Core: A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.Training: Instruction to develop new skills.
3 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2024-03-16T12:28:43.61+00:00

    See my article with source code

    https://dev.to/karenpayneoregon/sql-server-computed-columns-with-ef-core-3h8d

    Example from article

    internal class Context : DbContext
    {
        public DbSet<Person> Persons { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(ConnectionString())
                .EnableSensitiveDataLogging()
                .LogTo(message => Debug.WriteLine(message), LogLevel.Information)
                .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>()
                .Property(p => p.DisplayName)
                .HasComputedColumnSql("[Title] + ' ' + [FirstName] + ' ' + [LastName]");
    
            modelBuilder.Entity<Person>().HasData(
                new Person() { Id = 1, FirstName = "Karen", LastName = "Payne", Title = "Miss" },
                new Person() { Id = 2, FirstName = "Jane", LastName = "Adams", Title = "Miss" }
            );
    
        }
    }
    
    
    0 comments No comments