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
Developer technologies .NET Entity Framework Core
Community Center Not monitored
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.