实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > ASP.NET Core EFCore 属性配置

ASP.NET Core EFCore 属性配置与DbContext的用法详解

作者:CSharp精选营

实体属性配置是定义模型与数据库映射的核心,EFCore 提供两种方式:数据注解和 Fluent API,本文将深入探讨ASP.NET Core中EFCore的实体属性配置方法及DbContext的核心用法,感兴趣的朋友一起看看吧

本文将深入探讨 ASP.NET Core 中 EFCore 的实体属性配置方法及 DbContext 的核心用法,帮助开发者高效管理数据模型与数据库交互。

一、属性配置

实体属性配置是定义模型与数据库映射的核心,EFCore 提供两种方式:数据注解和 Fluent API

1. 数据注解(Data Annotations)

通过特性(Attributes)直接在实体类上声明配置,适合简单场景。

public class Product{    
[Key] // 主键    
public int Id { get; set; }
[Required, MaxLength(100)] // 非空且最大长度100    
public string Name { get; set; }
[ForeignKey("CategoryId")] // 外键    
public int CategoryId { get; set; }    
public Category Category { get; set; }}

常用注解:

2. Fluent API

在 DbContext 的 OnModelCreating 方法中配置,提供更灵活的方式。

protected override void OnModelCreating(ModelBuilder modelBuilder){   
 modelBuilder.Entity<Product>(entity =>    {       
 entity.HasKey(p => p.Id); // 主键   
     entity.Property(p => p.Name)           
   .IsRequired()          
    .HasMaxLength(100);
        entity.HasOne(p => p.Category) // 一对一/多关系        
      .WithMany(c => c.Products)          
    .HasForeignKey(p => p.CategoryId); 
   });}

常用配置方法:

优势:

二、DbContext 详解

DbContext 是 EFCore 的核心,负责数据库连接、查询、事务管理等。

1. 定义 DbContext

派生类需继承 DbContext,并暴露 DbSet<T> 属性。

public class AppDbContext : DbContext{    
public DbSet<Product> Products { get; set; }    
public DbSet<Category> Categories { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder options)        
=> options.UseSqlServer("Your_Connection_String");
    protected override void OnModelCreating(ModelBuilder modelBuilder)   
  {        
  // Fluent API 配置    
  }
}

2. 生命周期与依赖注入

在 ASP.NET Core 中,通过依赖注入管理上下文生命周期:

// Startup.cs
services.AddDbContext<AppDbContext>(options =>    
options.UseSqlServer(Configuration.GetConnectionString("Default")));

3. 数据操作

var products = await _context.Products.Where(p => p.Price > 50).ToListAsync();
_context.Products.Add(newProduct);
await _context.SaveChangesAsync();

关键方法:

4. 性能优化

services.AddDbContextPool<AppDbContext>(...);

三、高级配置

1. 多对多关系

使用 Fluent API 配置中间表:

modelBuilder.Entity<Post>()    
.HasMany(p => p.Tags)    
.WithMany(t => t.Posts)    
.UsingEntity(j => j.ToTable("PostTags"));

2. 继承映射

TPH(Table-Per-Hierarchy)模式:

modelBuilder.Entity<Blog>()    
.HasDiscriminator<string>("BlogType")    
.HasValue<Blog>("Standard")    
.HasValue<RssBlog>("RSS");

3. 全局过滤器

自动应用查询条件(如软删除):

modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);

四、最佳实践与常见问题

结语

掌握 EFCore 的属性配置与 DbContext 管理,能够显著提升数据层开发效率。合理选择配置方式,结合依赖注入和性能优化技巧,可构建高效稳健的 ASP.NET Core 应用。

到此这篇关于ASP.NET Core EFCore 属性配置与DbContext 详解的文章就介绍到这了,更多相关ASP.NET Core EFCore 属性配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文