使用EF Core定义默认值 - OnModelCreating

问题描述 投票:1回答:1

我开始从Asp.net MVC迁移到Asp.Net MVC Core,我意识到有些事情与我的预期有点不同。我想知道如何设置一些像我以前在EF 6中所做的那样的功能

        protected override void OnModelCreating(DbModelBuilder modelBuilder) 
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();                                                  
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

           modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();


        modelBuilder.Properties<string>().Configure(p => p.HasColumnType("varchar"));
        modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(100));
        modelBuilder.Properties().Where(x => x.Name == "Active").Configure(x => x.HasColumnType("char").HasMaxLength(1).IsRequired());
        modelBuilder.Properties().Where(x => x.Name == "Excluded").Configure(x => x.HasColumnType("char").HasMaxLength(1).IsRequired());
        modelBuilder.Properties().Where(x => x.Name == "RegisterDate").Configure(x => x.IsRequired());
        modelBuilder.Properties().Where(x => x.Name == "ChangeDate").Configure(x => x.IsRequired());


        ...
        } 

我似乎无法使用EF Core做到这一点

 protected override void OnModelCreating(ModelBuilder builder)
 {

 }

有谁知道我怎么能这样做?

c# asp.net-core asp.net-core-mvc entity-framework-core ef-core-2.0
1个回答
1
投票

它无法正常工作,因为您必须先为您的实体调用此行

var entityBuilder = modelBuilder.Entity<SomeEntity>();

然后执行以下操作:

entityBuilder.Property(someEntity => someEntity.SomeProperty)
             .HasColumnType("char")
             .HasMaxLength(10)
             .IsRequired();

另外看看IEntityTypeConfiguration<>它会帮助你保持你的DbContext干净。在你的DbContext OnModelCreating方法中,你只需要调用

modelBuilder.ApplyConfiguration(new SomeEntityConfiguration());

在此基础上,您还可以为公共属性定义基类,并为公共属性创建基本IEntityTypeConfiguration <>。那里没什么神奇的东西,但有些东西只是更明确地定义而非隐含。

© www.soinside.com 2019 - 2024. All rights reserved.