我是ASP/EF的新手.我在我的个人项目中使用ASP 5和Entity Framework 7.
所以我能够使用代码优先方法创建数据库和表,但是所有表名都是单数的,默认情况下不会复数.
在我的ServerMatrixDemoDB DbContext文件中,我在DBSets下面创建了:
public class ServerMatrixDemoDB : DbContext { public ServerMatrixDemoDB() { Database.EnsureCreated(); } public DbSetDomains { get; set; } public DbSet Environments { get; set; } public DbSet Networks { get; set; } public DbSet OsVersions { get; set; } public DbSet Tiers { get; set; } public DbSet Services { get; set; } public DbSet HardwareTypes { get; set; } public DbSet Powershell { get; set; } public DbSet DotNetVersions { get; set; } public DbSet Status { get; set; } public DbSet Servers { get; set; } public DbSet Applications { get; set; } }
在我的startup.cs文件中,我使用下面的代码:
public void ConfigureServices(IServiceCollection services) { services.AddMvc() // Add MVC Dependency. .AddJsonOptions( opt => { opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Api convert all property names to CamelCase. } ); services.AddLogging(); // Enable Logging for database errors. services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => { options.UseSqlServer(@"Server=.\SQLEXPRESS;user id=sa;password='passwrd';Database=ServerMatrixDemoDB;integrated security=True;"); }); services.AddTransient (); }
一旦我构建并运行项目,就会创建一个数据库和表,但所有表名都是单数.有没有办法在代码第一种方法中复数表名?
您可以在OnModelCreating重载中执行此操作,如 -
protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var entity in modelBuilder.Model.GetEntityTypes()) { modelBuilder.Entity(entity.Name).ToTable(entity.Name + "s"); } }
你也可以使用"数据注释"来做到这一点
[Table("blogs")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
或流利的Api
class MyContext : DbContext { public DbSetBlogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity () .ToTable("blogs"); } }
有关详细信息,请参阅 - EF7的文档