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

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

 

EF 6 Code-First系列文章目录:数据库

 

 

 

当咱们不想实体类中的某个或者某些属性,不要映射成数据库中的列的时候。能够使用NotMapped特性,标识NotMapped特性在属性上面就好了。默认状况下,EF为实体的每一个属性映射数据列。【必须包含get;和set;】。NotMapped特性重写了这个约定。app

NotMapped Attribute: [NotMapped()]ide

在上面的例子中,NotMapped特性应用在Student实体的Age属性上了,因此EF将不会在Students表中包含Age列:测试

须要注意的是:EF不会为没有get;和set;的属性,建立列。例以下面实体中的City和Age属性,都不会映射在数据库表的列中:ui

 咱们本身动手验证一下:spa

1.建立一个控制台应用程序EFAnnotationNotMapped,并安装EF.net

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.上下文类:3d

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

 

好了,你们有什么不明白的能够留言,我会一一回复,谢谢你们支持!

相关文章
相关标签/搜索