Nick Dewitt Nick Dewitt - 11 months ago 70
C# Question

Get default sql value from Entity Framework class

I am using a T4 template slightly modified from the one proposed in this answer to generate typescript interfaces from my EF POCOs.

The EF Core POCOs were generated database first, and some of the database columns have default values. These are correctly mapped by the EF generator into my context, e.g.


I'm a little confused about how to go about accessing the default value for a given EF class, i had thought
might do the trick but that's just giving the default value for the .net type.

I see there are some other solutions out there for getting this working but i can't seem to find one that yet works with ASP .Net Core.

Ideally, i would like to know how to determine if a property has a default EF value from it's MemberInfo, as the following line from the T4 template is generating the property descriptions it would be the easiest to modify that to output a default value for the TypeScript def.

foreach (MemberInfo mi in GetInterfaceMembers(t))
sb.AppendFormat(" {0}: {1};\n", mi.Name, GetTypeName(mi));

Answer Source

In case you have access to the generated DbContext, you can use the metadata provided by the DbContext.Model instead of reflection.

For instance:

foreach (var type in db.Model.GetEntityTypes())
    foreach (var property in type.GetProperties())
        var defaultValue = property.Relational().DefaultValue;

There are also a lot of useful methods like IModel.FindEntityType, IEnityType.FindProperty etc.