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属性也不能映射到数据库;

 

好了,大家有什么不明白的可以留言,我会一一回复,谢谢大家支持!

 

 

上一篇:9.5 翻译系列:数据注解之ForeignKey特性【EF 6 Code-First系列】
下一篇:9.3 翻译系列:数据注解特性之Key【EF 6 Code-First 系列】

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月20日 05时24分47秒