You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在DbContext中定义无需映射到数据库表的List集合

实现方案

你可以通过以下两种方式让EF忽略该属性的数据库映射,同时不影响正常访问:

方式一:使用[NotMapped]特性标注

直接给不需要映射的属性添加NotMapped特性即可,需先引用命名空间System.ComponentModel.DataAnnotations.Schema:

using System.ComponentModel.DataAnnotations.Schema;

public class YourCustomDbContext : DbContext
{
    public DbSet<z> name0 { get; set; }
    public DbSet<y> name1 { get; set; }

    // 加该特性后EF会完全忽略此属性的数据库映射
    [NotMapped]
    public List<x> name2 { get; set; } = new List<x>()
    {
        new x() {...},
        new x() {...},
        // 其余初始化逻辑
    };
}

方式二:使用Fluent API配置

如果不想在属性上直接加特性,可在OnModelCreating方法中配置忽略该属性:

public class YourCustomDbContext : DbContext
{
    public DbSet<z> name0 { get; set; }
    public DbSet<y> name1 { get; set; }
    public List<x> name2 { get; set; } = new List<x>()
    {
        new x() {...},
        new x() {...},
        // 其余初始化逻辑
    };

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 配置EF忽略name2属性的映射
        modelBuilder.Ignore<YourCustomDbContext>(c => c.name2);
        
        // 其余模型配置逻辑
    }
}

两种方案均会让EF在生成迁移、操作数据库时完全跳过该属性,不会生成对应表结构,也不会产生任何数据库相关的关联引用,你可以正常通过DbContext实例读写该属性。


内容的提问来源于stack exchange,提问作者Tom Naughton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 15:27:01