1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

First, thanks for the response. Users can be created by themselves or by others. When a user creates his own account, I want to set CreatedBy to UserId. However, when someone else creates the account, I want to set CreatedBy to the passed in Id. Thus, CreatedBy must accept an Id or use a default. HasComputedColumnSql will not accept a passed in value. Alternatively, I was hoping that HasDefaultValueSql could reference a column within the record (like UserId) for its value, but it cannot. Do you have any additional thoughts?
i think that if you have some business rules behind you better not do that inside the model builder, intead, do it when creating entities by using static heper method with sets the created by filed of the new entity by a value based on your business condition...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.