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

原文地址: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 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<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; }
}

转载于:https://www.cnblogs.com/JacZhu/p/5734845.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值