等同于modelBuilder的HasDefaultValueSql的Entity Framework Core属性是什么? [英] What is the Entity Framework Core attribute equivalent to modelBuilder's HasDefaultValueSql?

查看:73
本文介绍了等同于modelBuilder的HasDefaultValueSql的Entity Framework Core属性是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用注释为Entity Framework Core中的属性设置默认值.问题在于数据库未设置默认值,因此该值未向下传递到数据库层.

I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.

我想做类似于 modelBuilder HasDefaultValueSql :

[DefaultValue("400")]
public int LengthInMeters {get; set;}

如何将以下代码转换为属性?

How do you convert the below code to attributes?

modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");

单独使用默认值不起作用.我想单独使用属性,而不必弄乱迁移.

Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.

问题:我已经尝试使用EF进行其他方法,但是Entity Framework Core没有某些项目.例如 modelBuilder.Conventions AttributeToColumnAnnotationConvention CSharpMigrationCodeGenerator modelBuilder.Properties()

Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()

推荐答案

这就是我最终要做的有人提供了一种更清洁的方式,而不是密集的实施方式.

This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var property in entityType.GetProperties())
        {
            var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
            if (memberInfo == null) continue;
            var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
            if (defaultValue == null) continue;                   
            property.SqlServer().DefaultValue = defaultValue.Value;
        }
    }
}       

我可以使用默认值属性在数据库中设置默认值

I can set the default value in the database using the default value attribute

[DefaultValue("400")]
public int LengthInMeters {get; set;}

这篇关于等同于modelBuilder的HasDefaultValueSql的Entity Framework Core属性是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆