即使提供了DataAnnotations参数,Scaffold-DbContext也不会添加Table属性

时间:2017-07-10 04:38:39

标签: entity-framework .net-core entity-framework-core scaffolding asp.net-core-webapi

我在dotnet core EF6项目中搭建我的数据库,以便使用Scaffold-DbContext命令(逆向工程)生成我的模型。我正在尝试避免手动EntityTypeConfiguration,因此也提供了DataAnnotations参数。像:

Scaffold-DbContext "Data Source=localhostxx;...;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities -Context "MyDbContext" -f -Project Processor.Common -DataAnnotations

这将使用预期的属性(必需,长度等)来装饰生成的模型。但它不会在生成的类之上添加[Table("TableName")]属性。因此,我仍然需要提供手动配置,至少定义映射。例如:

//for Student table, I created DbSet prop in dbcontext class as:
public System.Data.Entity.DbSet<Student> Students { get; set; }

//configuration for Students DbSet
public class StudentConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Student>
{
    public StudentConfiguration ()
        : this("dbo")
    {
    }

    public StudentConfiguration (string schema)
    {
        ToTable("Student", schema);
    }
}

//then OnModelCreating
 modelBuilder.Configurations.Add(new StudentConfiguration());

如果我没有定义它,它会在db调用上抛出异常,说像这样的东西找不到表dbo.Student 。无论如何,生成的实体类默认有Table吗?所以我不必手动配置每个新表。

0 个答案:

没有答案