每天学一点,每天积累一点,进步就不止一点点!PS:好记性不如烂笔头,学会总结,学会思考~~~ ----要飞翔,必须靠自己!

灰太狼的梦想

好记性不如烂笔头,学会总结,学会思考~~~

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

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

 

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

 

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

 

 

posted @ 2019-04-06 11:00  灰太狼的梦想  阅读(2759)  评论(0编辑  收藏  举报