警告
This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef. 本文档是基于EF7版本.对于EF6.x及更早的版本请参见 http://msdn.com/data/ef.
注解
This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.
注解
The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared EntityFramework.Relational package).
Table Mapping¶
Table mapping identifies which table data should be queried from and saved to in the database.
In this article:
Conventions¶
By convention, each entity will be setup to map to a table with the same name as the entity.
Data Annotations¶
You can use Data Annotations to configure the table that a type maps to.
1 2 3 4 5 6 | [Table("blogs")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
|
You can also specify a schema that the table belongs to.
1 2 3 4 5 6 | [Table("blogs", Schema = "blogging")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
|
Fluent API¶
You can use the Fluent API to configure the table that a type maps to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.ToTable("blogs");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
|
You can also specify a schema that the table belongs to.
1 2 | modelBuilder.Entity<Blog>()
.ToTable("blogs", schema: "blogging");
|