警告
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.
Including & Excluding Types¶
Including a type in the model means that EF has metadata about that type and will attempt to read and write instances from/to the database.
In this article:
Conventions¶
By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included. Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.
- For example, in the following code listing all three types are discovered:
Blogbecause it is exposed in aDbSetproperty on the contextPostbecause it is discovered via theBlog.Postsnavigation propertyAuditEntrybecause it is mentioned inOnModelCreating
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AuditEntry>()
.Property(a => a.Username)
.IsRequired();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Blog Blog { get; set; }
}
public class AuditEntry
{
public int AuditEntryId { get; set; }
public string Username { get; set; }
public string Action { get; set; }
}
|
Data Annotations¶
You can use Data Annotations to exclude a type from the model.
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public BlogMetadata Metadata { get; set; }
}
[NotMapped]
public class BlogMetadata
{
public DateTime LoadedFromDatabase { get; set; }
}
|
Fluent API¶
You can use the Fluent API to exclude a type from the model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<BlogMetadata>();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public BlogMetadata Metadata { get; set; }
}
public class BlogMetadata
{
public DateTime LoadedFromDatabase { get; set; }
}
|