Ray*_*Ray 7 c# asp.net entity-framework entity-framework-core
我是ASP/EF的新手.我在我的个人项目中使用ASP 5和Entity Framework 7.
所以我能够使用代码优先方法创建数据库和表,但是所有表名都是单数的,默认情况下不会复数.
在我的ServerMatrixDemoDB DbContext文件中,我在DBSets下面创建了:
public class ServerMatrixDemoDB : DbContext
{
public ServerMatrixDemoDB()
{
Database.EnsureCreated();
}
public DbSet<Domain> Domains { get; set; }
public DbSet<Environment> Environments { get; set; }
public DbSet<Network> Networks { get; set; }
public DbSet<OsVersion> OsVersions { get; set; }
public DbSet<Tier> Tiers { get; set; }
public DbSet<Service> Services { get; set; }
public DbSet<HardwareType> HardwareTypes { get; set; }
public DbSet<Powershell> Powershell { get; set; }
public DbSet<DotNetVersion> DotNetVersions { get; set; }
public DbSet<Status> Status { get; set; }
public DbSet<Servers> Servers { get; set; }
public DbSet<Application> Applications { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我的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<ServerMatrixDemoDB>(options =>
{
options.UseSqlServer(@"Server=.\SQLEXPRESS;user id=sa;password='passwrd';Database=ServerMatrixDemoDB;integrated security=True;");
});
services.AddTransient<ServerMatrixDemoSeedData>();
}
Run Code Online (Sandbox Code Playgroud)
一旦我构建并运行项目,就会创建一个数据库和表,但所有表名都是单数.有没有办法在代码第一种方法中复数表名?
Pre*_*ngh 11
您可以在OnModelCreating重载中执行此操作,如 -
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
modelBuilder.Entity(entity.Name).ToTable(entity.Name + "s");
}
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用"数据注释"来做到这一点
[Table("blogs")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
或流利的Api
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.ToTable("blogs");
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅 - EF7的文档
归档时间: |
|
查看次数: |
5519 次 |
最近记录: |