2014年12月20日 星期六

[Mono Develop] 使用建立MariaDB當作asp.net Code First的資料庫(Vistual Studio Community 2013可適用)


我是用在Ubuntu下使用MonoDevelop (先前在winodw下裝mono run .net還是有點問題,查了之後在bug report上顯示尚待解決),所以你需要安裝MariaDB和Apache2和Mono和MonoDevelop,看看站內有沒有相關文件不然就Google一下。


進入主題:(Vistual Studio 2013步驟是差不多的)

1.首先在MonoDevelop下載 EntityFramework 和MySql Data Entity




















2.確認Package之中是否出現元件的參考






















3.建立一個Model/User類別,並建立Data Annotation的設定,以及加入以下參考

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;














4.建立一個DAL/MyContext類別

4.1加入以下參考
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;


4.2 MyContext 繼承DbContext並覆寫原有的連線字串為MyConnection

4.3 建立先前在Model/User中Dbset 物件





4.4 確認Web.config中的連線字串並確認provideName是有在entityFramework區段之中

 <connectionStrings>
    <add name="MyConnection" providerName="MySql.Data.MySqlClient" connectionString="server=[yourserver ip];port=3306;database=[db name];uid=[user];password=[password]"/>
  </connectionStrings>






















4.5 如果要Code First建立Table時自動將表格名稱加上s,就在OnModelCreating中加上

modelBuilder.Conventions.Add<PluralizingTableNameConvention>();











4.6 修改EntityFramework 的configuation設定,有兩種方法擇一即可

4.6.1 在MyContext的類別上加上

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]













4.6.2 或是在Globa.asax中的Application Start中加上

DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration());












5. 在web.config之中增加區段資料

5.1 在configSection中加上entityFramework區段宣告

<section name="entityFrameworktype="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089requirePermission="false/>








5.2 在entityFramework區段中加上

<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
  <!--- 初始化的資料-->

       <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"/>
           <providers>
       <provider invariantName="MySql.Data.MySqlClient"
type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
    </providers>
  </entityFramework>













5.3 在entityFramework區段中加上context的內容

<context type="你的完整類別名稱, 你的組仵名稱">














5.4 在</entityFramework>後面 </configuration>的前面加上<system.data>的內容,移除舊的mysql組仵再換成新的(此步驟只有按照上面設定但仍然會有錯誤時再加即可,有時侯組仵會寫在machine.config之中所以會導致版本不一致的錯誤











6. 最後在controller中新增一筆資料,看看是否正常建立users名稱的表格,以及新增的資料














接著就可以用Code First的方式來寫程式囉!


沒有留言:

張貼留言

熱門文章