
9.4 翻译系列:EF 6以及 EF Core中的NotMapped特性(EF 6 Code-First系列)
发布日期:2021-05-09 01:04:05
浏览次数:16
分类:博客文章
本文共 2082 字,大约阅读时间需要 6 分钟。
原文链接:
EF 6 Code-First系列文章目录:
- )
- )
- )
- )
当我们不想实体类中的某个或者某些属性,不要映射成数据库中的列的时候。可以使用NotMapped特性,标识NotMapped特性在属性上面就行了。默认情况下,EF为实体的每个属性映射数据列。【必须包含get;和set;】。NotMapped特性重写了这个约定。
NotMapped Attribute: [NotMapped()]
在上面的例子中,NotMapped特性应用在Student实体的Age属性上了,所以EF将不会在Students表中包含Age列:
需要注意的是:EF不会为没有get;和set;的属性,创建列。例如下面实体中的City和Age属性,都不会映射在数据库表的列中:
我们自己动手验证一下:
1.创建一个控制台应用程序EFAnnotationNotMapped,并安装EF
2.创建一个Student类
public class Student { [Key] public int Key { get; set; } public string Name { get; set; } [NotMapped] public string Sex { get; set; } public int Age { get; set; } }
3.上下文类:
public class EFDbContext:DbContext { public EFDbContext() : base("name=Constr") { Database.SetInitializer(new DropCreateDatabaseAlways ()); } public DbSet Students { get; set; } }
4.配置文件:
5.测试代码:
6.运行程序:
看看生成的数据库:
可以看到标注了NotMapped的Sex属性没有映射到数据表的列中。
来看看没有get和set的属性的情况:修改Student实体
public class Student { private string _myschool; private string _myHobby; [Key] public int Key { get; set; } public string Name { get; set; } [NotMapped] public string Sex { get; set; } public int Age { get; set; } public string MySchool { get { return _myschool; } } public string MyHobby { set { _myHobby = value; } } }
运行程序:
看看数据库:可以看到MySchool和MyHobby没有映射为数据列。
再看看private属性的情况,添加一个private属性Address
public class Student { private string _myschool; private string _myHobby; [Key] public int Key { get; set; } public string Name { get; set; } [NotMapped] public string Sex { get; set; } public int Age { get; set; } public string MySchool { get { return _myschool; } } public string MyHobby { set { _myHobby = value; } } private string Address { get; set; } }
运行程序:
看看数据库:可以看到Private属性也不能映射到数据列。
总结:
1. NotMapped特性标识的属性列,不会映射到数据库
2.没有get;set;的属性不能映射到数据库;
3.private属性也不能映射到数据库;
好了,大家有什么不明白的可以留言,我会一一回复,谢谢大家支持!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2025年04月20日 05时24分47秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
MacOS 应对系统无响应的方法
2019-03-14
使用KeyShot调整一个场景中的照明亮度
2019-03-14
Mac隐藏辅助功能|自定义苹果Mac显示器
2019-03-14
ActivityNotFoundException异常错误
2019-03-14
git远程仓库切换
2019-03-14
带照片捕捉功能的ESP32-CAM PIR运动检测器
2019-03-15
如何使用SSH远程管理Linux服务器
2019-03-15
降级到旧版本macOS的3种方法
2019-03-15
学习Vue.js2.0(国外视频教程)
2019-03-15
wxPython和PyOpenGL视频
2019-03-15
在30分钟内学习PHP
2019-03-15
Python http.server 服务器
2019-03-15
Python svm 支持向量机
2019-03-15
OpenStack 最小化安装配置(一):物理机网桥配置
2019-03-15
PS快速美白照片
2019-03-15
ubuntu 16.04 镜像下载
2019-03-15
CUDA9.1、cuDNN7在Ubuntu16.04上的安装
2019-03-15
微信小程序云开发:怎么删除云函数?已解决
2019-03-15