EntityFramework Core 学习笔记 —— 包含与排除类型

时间:2021-12-11 16:33:03

原文地址:[https://docs.efproject.net/en/latest/modeling/included-types.html][1]


在模型类中包含一种类型意味着 EF 拥有了这种类型的元数据并且将尝试在数据库中进行读写类型的实例。

内容导航

  • [约定][2]
  • [Data Annotation][3]
  • [Fluent API][4]

约定

根据约定,暴露在你的上下文的 `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 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.
*最后一句话好像翻译的有问题*

举个栗子!在下面的代码中,所有的三个类型都将会被发现

  • 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 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; }

}



  [1]: https://docs.efproject.net/en/latest/modeling/included-types.html
[2]: #1
[3]: #2
[4]: #3