efcore icon indicating copy to clipboard operation
efcore copied to clipboard

DatabaseGeneratedOption ... Option for SQL-managed column defaults?

Open pjevans opened this issue 5 years ago • 2 comments

We're doing a full db SQL project alongside a .NET5 web app project. We want to have all of the database column defaults be set in the db project. We had issues in our older project where EF just wouldn't allow the DB to do it's own defaults, our fix was to put the default (duplicating) into the class itself per column. That's not what we wanted. We also looked into DatabaseGeneratredOption and tested each of those options. The one that gives us the outcome that we are expecting is frankly 'Identity'. But it doesn't 'sound' right. These aren't identity columns, but setting to Identity will allow us to set the column if we need to, and if we don't, EF allows the database to do its default as set there. Identity seems to be doing exactly what we want, but we're not sure if it's also doing something that we are unaware of that is specific to identity in EF. Just concerned before we devote the app to that decoration as the solution to this. However, we also feel this is such a normal thing, there should be a real option added for this use-case.

Example:

-- ::::DB::::  We want to allow this....
[dbsShema].[Company].[LogoUrl] VARCHAR(450) DEFAULT 'https://some.awesome.com/pic.png'
// ::::Model:::::  by doing this....
public class Company
{
     // ....
     [DatabaseGenerated(DatabaseGeneratedOption.DbDefault)]
     public string LogoUrl { get; set; }
     // ..... 
}

Behavior: If LogoUrl is NULL on insert, allow the insert as the DB has defined defaults. if LogoUrl is set, save whatever is in the class during the insert. (the experience we're seeing with .Identity).

pjevans avatar May 18 '21 14:05 pjevans

DatabaseGeneratedOption.Identity is the correct configuration for this.

Unfortunately we cannot change or add values for this enum due to compatibility issues.

Alternatively you can call .ValueGeneratedOnAdd() using Fluent API. See https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=fluent-api#explicitly-configuring-value-generation

AndriySvyryd avatar May 18 '21 20:05 AndriySvyryd

Ahh... ok cool. Good to know. Learned something today.

pjevans avatar May 18 '21 20:05 pjevans