能否在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
相关产品推荐
相关产品推荐

