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屬性也不能映射到數據庫;

 

好了,大家有什么不明白的可以留言,我會一一回復,謝謝大家支持!

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM