EntityFrameworkCore中的OnModelCreating

EntityFrameworkCore中的OnModelCreating

在我们使用EntityFrameworkCore作为数据库ORM框架的时候,不可避免的要重载DbContext中的一个虚方法OnModelCreating,那么这个方法到底是做什么的?到底有哪些作用呢?带着这些问题我们来看看在EntityFrameworkCore到底该如何使用OnModelCreating这个方法,首先我们来看看Microsoft.EntityFrameworkCore命名空间下面的DbContext中关于OnModelCreating的定义及注释。

/// <summary>
    ///     Override this method to further configure the model that was discovered by convention from the entity types
    ///     exposed in <see cref="T:Microsoft.EntityFrameworkCore.DbSet`1" /> properties on your derived context. The resulting model may be cached
    ///     and re-used for subsequent instances of your derived context.
    /// </summary>
    /// <remarks>
    ///     If a model is explicitly set on the options for this context (via <see cref="M:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel)" />)
    ///     then this method will not be run.
    /// </remarks>
    /// <param name="modelBuilder">
    ///     The builder being used to construct the model for this context. Databases (and other extensions) typically
    ///     define extension methods on this object that allow you to configure aspects of the model that are specific
    ///     to a given database.
    /// </param>
    protected internal virtual void OnModelCreating(ModelBuilder modelBuilder)
    {
    }

按照官方的解释:在完成对派生上下文的模型的初始化后,并在该模型已锁定并用于初始化上下文之前,将调用此方法。 虽然此方法的默认实现不执行任何操作,但可在派生类中重写此方法,这样便能在锁定模型之前对其进行进一步的配置。通常,在创建派生上下文的第一个实例时仅调用此方法一次, 然后将缓存该上下文的模型,并且该模型适用于应用程序域中的上下文的所有后续实例另外在做数据库迁移生成迁移文件的时候也会调用OnModelCreating方法。通过在给定的 ModelBuidler 上设置 ModelCaching 属性可禁用此缓存,但注意这样做会大大降低性能。 通过直接使用 DbModelBuilder 和 DbContextFactory 类来提供对缓存的更多控制。那么这些深度的自定义配置有哪些方面的内容呢?

详见链接

https://www.cnblogs.com/seekdream/p/10641510.html

### 关于 Entity Framework Core 的使用教程和最佳实践 #### 什么是 Entity Framework Core? Entity Framework Core 是微软推出的轻量级、跨平台 ORM(对象关系映射)框架,作为早期 Entity Framework 的后续版本,它专为 .NET Core 应用程序设计并提供支持[^1]。 --- #### 如何安装 Entity Framework Core? 可以通过 NuGet 包管理器来安装 EF Core。以下是基本命令: ```bash dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` 上述命令分别用于安装核心库以及针对 SQL Server 数据库的支持包[^4]。 --- #### 创建数据库上下文 在 EF Core 中,`DbContext` 类是访问数据库的主要入口点。以下是一个简单的 `DbContext` 实现示例: ```csharp using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("YourConnectionStringHere"); } } ``` 在此代码片段中,定义了一个名为 `ApplicationDbContext` 的类,并设置了连接字符串以指定目标数据库。 --- #### 建立实体模型 EF Core 支持通过 Code First 方法创建数据模型。例如,可以定义如下产品实体: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` 当运行应用程序时,EF Core 将自动生成对应的数据表结构。 --- #### 多对多关系的实现 为了设置多对多关系,通常需要引入一个中间表。下面展示如何配置这种关联方式: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<StudentCourse>() .HasKey(sc => new { sc.StudentId, sc.CourseId }); modelBuilder.Entity<StudentCourse>() .HasOne(sc => sc.Student) .WithMany(s => s.Courses) .HasForeignKey(sc => sc.StudentId); modelBuilder.Entity<StudentCourse>() .HasOne(sc => sc.Course) .WithMany(c => c.Students) .HasForeignKey(sc => sc.CourseId); } public class StudentCourse { public int StudentId { get; set; } public Student Student { get; set; } public int CourseId { get; set; } public Course Course { get; set; } } ``` 此方法利用 Fluent API 明确指定了学生与课程之间的多对多联系[^5]。 --- #### 单元测试中的 Mocking 技术 对于基于 EF Core 开发的应用程序来说,在编写单元测试期间可能需要用到模拟技术。借助第三方工具如 **Moq.EntityFrameworkCore**,能够轻松完成这一需求[^3]。 --- #### 性能优化建议 - 减少不必要的查询操作次数。 - 利用显式加载代替贪婪加载机制。 - 对频繁使用的 LINQ 查询考虑预编译选项。 以上策略有助于提升系统的整体性能表现[^2]。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值