Search code examples
entity-frameworkfluent-interface

In EntityFramework 2.1 Fluent API Setting Audit Fields on Insert


Using Entity Framework's Fluent API, I can successfully insert a new row in the user's table using this code:

 modelBuilder.Entity<User>().ToTable("Users");
 modelBuilder.Entity<User>().HasKey(x => x.UserId);

However, I also want to set the CreatedBy field based on the Guid assigned to the UserId. The following code does not work:

 modelBuilder.Entity<User>().Property(x => x.CreatedBy)
      .HasDefaultValueSql("SCOPE_IDENTITY()");

I would appreciate any suggestions. Thanks.


Solution

  • This can be done using the .HasComputedColumnSql.

    Example:

    modelBuilder.Entity<Contact>()
                .Propery(p => p.LastModified)
                .HasComputedColumnSql("GetUtcDate()");
    
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SalesOrderHeader>()
        .Property(e => e.SalesOrderNumber)
        .HasComputedColumnSql("isnull(N'SO'+CONVERT([nvarchar](23),[SalesOrderID]),N'*** ERROR ***')");
    }
    

    Here is the link you can refer to:

    HasComputedColumnSql Method

    hope this helps,

    HK