The Fluent API ValueGeneratedOnAddOrUpdate Method

The Entity Framework Core Fluent API ValueGeneratedOnAddOrUpdate provides a way to indicate that the value for the selected property will be generated whenever a new entity is added to the database or an existing one is modified. Therefore the property should not be included in INSERT or UPDATE statements when SQL is generated by EF Core.

In the following example, the LastAccessed column in the database can be assumed to have a default constraint set up to apply a value when the contact is first created, and a trigger to update it every time the row is accessed thereafter. Consequently, it has been configured to be excluded from INSERT and UPDATE statements by EF Core through the application of the ValueGeneratedOnAddOrUpdate method:

public class SampleContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>()
            .Property(p => p.LastAccessed)
            .ValueGeneratedOnAddOrUpdate();
    } 

    public class Contact
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; } 
        public DateTime LastAccessed { get; set; }
    }
}

Entity Framework Core does not implement a value generation strategy. Database providers differ in the way that values are automatically generated. Some will generated values for selected data types such as Identity, rowversion, GUID. Others may require manual configuration such as setting default values or triggers.

If you set a value for the property configured as ValueGeneratedOnAddOrUpdate while the entity is being tracked by the context, the property and the value that you set will be included in any INSERT and UPDATE statements. This value may be saved in the database, depending on how you have configured your value generation strategy. This is only applicable if the value that you provide is not the CLR default value for the data type of the property.

Data Annotations

The Data Annotations attribute equivalent of the ValueGeneratedOnAddOrUpdate method is the DatabaseGenerated attribute with the Computed option.

Previous Versions

In previous versions of Entity Framework, you would use the HasDatabaseGenerated method with the DatabaseGenerated.Computed enumeration to achieve the same outcome as the Entity Framework core ValueGeneratedOnAddOrUpdate method.


Created:
Last updated: 14/03/2017 16:33:45
Proficiency Level: Beginner