Entity Framework Fluent API and Indexing

本文介绍如何使用Entity Framework (EF) 的 Fluent API 来为 People 实体类的不同属性定义单列索引、多列索引、唯一索引及聚集索引,并讨论了当前版本 EF 中尚不支持的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class People  
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string PhoneNumber { get; set; }
    public string NationalInsuranceNo { get; set; }
}


Single column Indexes


modelBuilder.Entity<People>()  
    .Property(x => x.Firstname)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("ix_people_firstname")));


Multi Column Indexes


modelBuilder.Entity<People>()  
    .Property(x => x.Firstname)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("ix_people_fullname", 1)));
modelBuilder.Entity<People>()  
    .Property(x => x.Lastname)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("ix_people_fullname", 2)));


Unique Indexes


modelBuilder.Entity<People>()  
    .Property(x => x.NationalInsuranceNo)
    .HasColumnAnnotation("Index",
        new IndexAnnotation(new IndexAttribute("ix_people_nationalinsurance") {IsUnique = true}));

Clustered Indexes

modelBuilder.Entity<People>()  
    .Property(x => x.Id)
    .HasColumnAnnotation("Index",
        new IndexAnnotation(new IndexAttribute("ix_people_nationalinsurance") { IsClustered = true}));

What's Not Possible Using Fluent API

As of Entity Framework 6.1.1

  • Include Fields
  • Sort Order (ASC,DESC)
  • Filtered Indexes

Whilst this is a big step forwards it still feels like a work in progress. I would hope to end up with a friendlier and more complete syntax for doing this something like...




<think>嗯,用户想了解Entity Framework Core中的Fluent API的用法和功能,需要教程、功能详解和示例。首先,我得回忆一下Fluent API在EF Core中的作用。Fluent API主要用于配置模型,相比数据注解,它更灵活,能处理更复杂的映射关系。比如设置主键、外键、索引,或者配置关系,如一对一、一对多等。 根据引用内容,引用[2]提到EF Core更注重Fluent API作为主要的模型定义方式,而引用[3]则给出了一个配置一对多关系的例子。可能需要先介绍Fluent API的基本概念,然后分点讲解常用配置功能,比如实体配置、属性配置、关系配置等,每个部分都要有示例代码。 用户可能需要知道如何在DbContext的OnModelCreating方法中使用modelBuilder,比如modelBuilder.Entity<Post>()这样的结构。然后每个配置项,如主键、列名、是否必需、最大长度等,都要用Fluent API的方法,比如.HasKey(), .Property(), .HasColumnName()等。 另外,关系配置部分比较复杂,需要详细说明HasOne、WithMany、HasForeignKey等方法的使用,可能还需要对比数据注解的方式,说明为什么Fluent API更强大。例如,配置复合主键只能用Fluent API,数据注解无法做到。 索引配置也是一个重点,比如.HasIndex()和.IsUnique(),可以提到EF Core支持索引过滤,比如在软删除中过滤已删除的记录。 还要注意代码示例的正确性,比如在引用[3]中的示例代码里,配置了一对多关系,但可能用户需要更多的例子,比如多对多关系的配置,或者继承策略的配置。 另外,用户可能需要了解Fluent API的优势,比如集中管理配置、避免污染实体类、支持复杂场景等,这些在引用[3]和引用[2]中都有提及。 需要确保回答结构清晰,分点列出,每个功能点配合示例代码,并引用相关的引用来源。比如在讲解索引时,可以引用[3]中的内容,说明EF Core支持Fluent API配置索引。 最后,生成相关问题要考虑用户可能的后续疑问,比如性能优化、与数据注解的比较、复杂关系配置等,参考之前的引用内容,比如引用[1]提到性能优化,可以生成相关问题。</think>### EntityFramework Core Fluent API 使用详解 #### 一、Fluent API 基础概念 Fluent API 是 EF Core 中用于配置实体类和数据库映射的核心工具,通过链式方法调用实现更灵活的模型定义。相较于数据注解,它能处理更复杂的场景(如复合主键、多对多关系)[^2]。 #### 二、核心配置功能及示例 1. **实体配置** ```csharp modelBuilder.Entity<Post>() .ToTable("BlogPosts") // 指定表名 .HasKey(p => p.PostId); // 定义主键 ``` 2. **属性配置** ```csharp modelBuilder.Entity<Post>() .Property(p => p.Title) .HasColumnName("PostTitle") // 自定义列名 .HasMaxLength(100) // 最大长度 .IsRequired(); // 非空约束 ``` 3. **关系配置** - **一对多**(博客-文章)[^3]: ```csharp modelBuilder.Entity<Blog>() .HasMany(b => b.Posts) .WithOne(p => p.Blog) .HasForeignKey(p => p.BlogId); ``` - **一对一**(用户-档案): ```csharp modelBuilder.Entity<User>() .HasOne(u => u.Profile) .WithOne(p => p.User) .HasForeignKey<Profile>(p => p.UserId); ``` 4. **索引配置** ```csharp modelBuilder.Entity<Post>() .HasIndex(p => p.Slug) // 单列索引 .IsUnique(); // 唯一索引 modelBuilder.Entity<Product>() .HasIndex(p => new { p.Category, p.Price }) // 复合索引 .HasFilter("IsDeleted = 0"); // 过滤索引(软删除场景) ``` 5. **继承策略** ```csharp modelBuilder.Entity<Animal>() .UseTphMappingStrategy(); // Table-Per-Hierarchy ``` #### 三、高级功能 - **忽略字段**:`modelBuilder.Entity<Post>().Ignore(p => p.TempData);` - **并发令牌**:`.Property(p => p.RowVersion).IsConcurrencyToken()` - **默认值**:`.Property(p => p.CreateTime).HasDefaultValueSql("GETDATE()")` #### 四、最佳实践 1. **集中配置**:通过`IEntityTypeConfiguration<T>`接口分离配置类 ```csharp public class PostConfiguration : IEntityTypeConfiguration<Post> { public void Configure(EntityTypeBuilder<Post> builder) { builder.HasQueryFilter(p => !p.IsDeleted); // 全局过滤 } } ``` 2. **性能优化**:结合`AsNoTracking()`使用可提升只读查询效率[^1] ```csharp // 示例上下文配置 protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); } ``` §§ 1. 如何通过Fluent API实现多对多关系配置? 2. Fluent API与数据注解的主要区别是什么? 3. EF Core中如何配置全局查询过滤器? 4. 使用Fluent API时如何管理大型项目的配置复杂度? 5. Fluent API支持哪些类型的数据库约束配置? 参考文献: : 禁用EF Core更改跟踪的查询优化方法 : EF Core与EF6的架构对比 : Fluent API实现关系映射的代码示例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值