EntityFramework CodeFirst 4.3 step by step (1)


自CodeFirst推出以來,一直以來都想去學一學用一用,苦於一直被各種事情所羈絆(當然這不是理由啦!)而delay。。。

最近跳槽到一家德資企業,進項目組后主要在做一個船舶信息管理和控制類的軟件,客戶是挪威佬。項目中就用到了codefirst4.2,真心覺得老外相當地與時俱進啊!!! 於是再也忍不住了,要來好好玩一玩CodeFirst,為了督促我自己學習,我向園子里的各位博友保證會將CodeFirst這個系列寫完整,懇請大家監督和鞭策我吧,哈哈!

下面一段時間,我會帶着如下幾個問題去學習CodeFirst4.3:

1. What's the advantage of codefirst.

2. How to config and use.

3. How to migrate.

4. How to use in project.

 


 

下面正式開始我們的CodeFirst之旅:

1. What's the advantage of codefirst.

CodeFirst顧名思義是代碼優先,它擯棄了傳統的項目開發模式中諸如ER模型,DB設計等過程,讓我們直接從DomainModel也就是領域模型開始開發。沒有了數據庫設計這個環節,我們程序員和領域專家在進行每一次溝通之后,都可以很快地抽象出領域模型,並實現相應的功能,然后我們再利用CodeFirst提供的功能反向生成數據庫。

從這個過程我們可以看出CodeFirst有以下幾點優勢:

開發速度:我們程序員在此時暫時不需要具備DBA相關技能,直接上代碼(程序員最喜歡的啦)。

代碼清晰可控制:沒有EntityFramework自動生成的Entity類,取而代之的是我們自己根據領域模型設計出的DomainModel。

和edmx model說再見:還記得edmx model嗎?每次數據庫有改動都要去維護這個東西,如果開發是大家連的是同一個數據庫的話經常會出現數據庫更新和edmx model更新不同步(這個我以前公司的兄弟們應該相當有體會哈)。

 

2. How to config and use.

配置和使用網上一搜到處都是,但幾乎都只同一個版本,不知道是哪個在搞批發的,用的都是Sql Express,我們實際項目中Sql Server Instance很少有完整的demo。

廢話不多說了,下面來講講CodeFirst4.3具體的配置和使用。

1. 添加EntityFramework4.3的引用,沒有的話裝一個NuGet就什么都有了。

2. System.ComponentModel.DataAnnotations,System.Data.Entity引用添加了嗎?沒有的話趕緊添加吧!

3. System.Data.SqlServerCe.Entity.dll這個程序集的引用肯定沒有吧,是程序員不要說找不到哦,如果找不到直接email to me,我發你得了!

4. 上面這些reference都添加后,再來修改config文件(根據project的類型可以是app.config或者web.config)

app.config
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <configSections>
 4     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 5     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 6   </configSections>
 7   <!--<entityFramework>
 8     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
 9       <parameters>
10         <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
11       </parameters>
12     </defaultConnectionFactory>
13   </entityFramework>-->
14 
15   <connectionStrings>
16     <add name="BlogDB" connectionString="Data Source=.;Initial Catalog=BlogDB;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
17   </connectionStrings>
18   <system.data>
19     <DbProviderFactories>
20       <remove invariant="System.Data.SqlServerCe.4.0" />
21       <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
22     </DbProviderFactories>
23   </system.data>
24 </configuration>

這個折騰了我一個多小時,不解釋,照做准沒錯!

5. 配置OK,下面可以開始舒舒服服地寫代碼啦!

假設我們做一個 Blog系統,和領域專家討論后抽象出一個DomainModel為Blog

Blog
1     class Blog
2     {
3         public int BlogId { get; set; }
4         public string Name { get; set; }
5     }

根據以前的經驗,這個應該是數據庫中的一張表,那么我們如何生成一張Blogs表呢?

我們需要一個繼承自DbContext的類,並且有一個屬性

BlogContext
1     class BlogContext : DbContext
2     {
3         public BlogContext()
4             : base("BlogDB")   //the name shall be equal to the name of connectionstring in config file.
5         {
6         }
7 
8         public DbSet<Blog> Blogs { get; set; }
9     }

我用的是一個控制台程序,那就在main函數里面進行一次數據庫插入操作

Program
 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             using (var db = new BlogContext())
 6             {
 7                 db.Blogs.Add(new Blog { Name = "Another Blog " });
 8                 db.SaveChanges();
 9 
10                 foreach (var blog in db.Blogs)
11                 {
12                     Console.WriteLine(blog.Name);
13                 }
14 
15                 Console.ReadLine();
16             }
17         }
18     }

打開數據庫,BlogDB乖乖地在那里躺着了!
至此,我們已經算是嘗試了一把CodeFirst,但問題來了,如果我加一個User類,難道非要進行一次數據庫操作嗎?

CodeFirst4.3當然不會這么弱了,它提供了強大的Migration功能來完成數據庫的更新,從而讓我們遠離EntityFramework時代去維護edmx model的痛苦。同時也改變需求變更帶來的數據庫、代碼同步更改的囧境。

下一節我們來講Migration。


免責聲明!

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



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