原文地址:https://docs.efproject.net/en/latest/modeling/included-types.html
在模型类中包含一种类型意味着 EF 拥有了这种类型的元数据并且将尝试在数据库中进行读写类型的实例。
内容导航
约定
根据约定,暴露在你的上下文的 DbSet
属性中的类型将会被包含入你的模型中。此外,在 OnModelCreating
方法中涉及到的类型也会被包含进来。最终,任何在已被发现的类型被递归查找到的属性的类型也会被包含在模型中。
By convention, types that are exposed in
DbSet
properties on your context are included in your model. In addition, types that are mentioned in theOnModelCreating
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.
最后一句话好像翻译的有问题
举个栗子!在下面的代码中,所有的三个类型都将会被发现
Blog
,因为它暴露在上下文的DbSet
属性中Post
,因为它被Blog.Posts
这个导航属性找到AuditEntry
,因为它在OnModelCreating
涉及到了
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; } // 人工高亮
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AuditEntry>(); // 人工高亮
}
}
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 Annotation
我们也可以通过 Data Annotations 来从模型中排除一个类型
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
我们也可以使用 Fluent API 从模型中排除一个类型。
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; }
}