首页 > 移动平台 > 详细

9.4 翻译系列:EF 6以及 EF Core中的NotMapped特性(EF 6 Code-First系列)

时间:2019-04-06 11:45:43      阅读:181      评论:0      收藏:0      [点我收藏+]

原文链接:http://www.entityframeworktutorial.net/code-first/notmapped-dataannotations-attribute-in-code-first.aspx

当我们不想实体类中的某个或者某些属性,不要映射成数据库中的列的时候。可以使用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<EFDbContext>(new DropCreateDatabaseAlways<EFDbContext>());
        }

        public DbSet<Student> Students { get; set; }
    }

4.配置文件:

 <connectionStrings>
    <add name="Constr" connectionString="server=.;database=EFAnnotationNotMappedDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>
  </connectionStrings>

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.4 翻译系列:EF 6以及 EF Core中的NotMapped特性(EF 6 Code-First系列)

原文:https://www.cnblogs.com/caofangsheng/p/10661103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!