从实体框架类获取默认的SQL值 [英] Get default sql value from Entity Framework class
问题描述
我正在使用从此答案中提出的模板稍作修改的T4模板,以从我的EF POCO生成打字稿界面
I am using a T4 template slightly modified from the one proposed in this answer to generate typescript interfaces from my EF POCOs.
EF核心POCO首先生成数据库,并且某些数据库列具有默认值。这些由EF生成器正确映射到我的上下文中,例如 .HasDefaultValueSql( 0)
;
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. .HasDefaultValueSql("0")
;
我对如何访问默认值有些困惑给定EF类的值,我曾想过 GetValueOrDefault
可以解决问题,但这只是为.net类型提供默认值。
I'm a little confused about how to go about accessing the default value for a given EF class, i had thought GetValueOrDefault
might do the trick but that's just giving the default value for the .net type.
我看到还有其他一些解决方案可以使此工作正常进行,但我似乎找不到能与ASP .Net Core一起使用的解决方案。
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.
理想情况下,我想知道如何从其MemberInfo中确定某个属性是否具有默认EF值,因为T4模板的以下行正在生成属性描述,因此最容易修改该属性以输出默认值
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));
}
推荐答案
如果您有权访问生成的 DbContext
,您可以使用 DbContext.Model
提供的元数据来代替反射。
In case you have access to the generated DbContext
, you can use the metadata provided by the DbContext.Model
instead of reflection.
例如:
foreach (var type in db.Model.GetEntityTypes())
{
foreach (var property in type.GetProperties())
{
var defaultValue = property.Relational().DefaultValue;
}
}
还有很多有用的方法,例如 IModel.FindEntityType
, IEnityType.FindProperty
等
There are also a lot of useful methods like IModel.FindEntityType
, IEnityType.FindProperty
etc.
这篇关于从实体框架类获取默认的SQL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!