关于EF代码优先默认值的问题

我是小数位 2017-10-17 10:42:33
 /// <summary>
/// 是否是有效厂家(投标人)原因说明
/// </summary>
[MaxLength(300)]
[DefaultValue("")]
public string YNRemark { get; set; }

假如mode中我有以上字段,我想在数据库中同时也生默认值,类似如下
create table test(YNRemark varchar(300) not null default ''),请问我应该如何做?
我希望不要每个字段都去设置一变
最好如下面我指定的小数位例子

/// <summary>
/// 用于modelBuilder全局设置自定义精度属性
/// </summary>
public class DecimalPrecisionAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration, DecimalPrecisionAttribute attribute)
{
if (attribute.Precision < 1 || attribute.Precision > 38)
{
throw new InvalidOperationException("Precision must be between 1 and 38.");
}
if (attribute.Scale > attribute.Precision)
{
throw new InvalidOperationException("Scale must be between 0 and the Precision value.");
}
configuration.HasPrecision(attribute.Precision, attribute.Scale);
}
}

在onmodelcreating加一句话就好了
modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//生成自己定义的表名
modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());

//设置字段映射
modelBuilder.Entity<Plan>()
.Property(u => u.StartDate)
.HasColumnName("StarDate");
//生成存储过程 var destinations = context.Database.SqlQuery<DestinationSummary>("dbo.GetDestinationSummary @p0, @p1", country, keyWords);
modelBuilder.Entity<SysLog>().MapToStoredProcedures();

}
...全文
430 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_18285019 2021-06-30
  • 打赏
  • 举报
回复

ef有点坑,应该给数据库默认值带到 代码中,有些想用默认的 就不用 填写了,不知道微软为啥不给同步默认值

丰云 2017-11-03
  • 打赏
  • 举报
回复
我是小数位 2017-11-03
  • 打赏
  • 举报
回复
掉到坑里了,没人回的
我是小数位 2017-10-18
  • 打赏
  • 举报
回复
怎么没人回我啊

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧