Entity Framework 代碼優先 實現數據庫

二,引用dll:

    1、採用Nuget安裝EF6.0.2;

    2、採用Nuget安裝MySql.Data.Entity.EF6

    注意:要採用Nuget進行安裝,否則可能會缺少相應的dll或者是配置信息

二、配置 web.config或app.config

    1、將entitframework節點替代爲:

 <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">

    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>

    <providers>

      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />

      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />

    </providers>

  </entityFramework>    


    2、添加 ConnectionString節點:

<connectionStrings>

    <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=數據庫名稱;user id=Mysql的登錄用戶名;password=Mysql server密碼;" providerName="MySql.Data.MySqlClient"/>  連接mySQL 數據庫

 <add name="TestDB" connectionString="Data Source=.;Initial Catalog=MyTest;User ID=sa;Password=123456;" providerName="System.Data.SqlClient"/> MSSQL 數據庫

  </connectionStrings>


三 建立模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DBModel
{
     [Table("UserInfo")]
    public  partial class UserInfo
    {
        [Key]
        [Column(TypeName = "uniqueidentifier")]
         Guid id { get; set; }
        [Column(TypeName = "nvarchar")]
        [MaxLength(50)]
        string userName{get;set;}

        [Column(TypeName = "nvarchar")]
        [MaxLength(50)]
        [DataType(DataType.Password)]
        string password { get; set; }
    }

}






四 建立數據上下文

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using DBModel;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Infrastructure;
namespace DB
{
    public partial class DBContext :DbContext
    {
        public DBContext()
            : base("name=TestDB")
        {
        }

        DbSet<UserInfo> UserInfo { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//移除複數表名的契約    不允許將表名變爲複數形式  默認爲UserInfos            modelBuilder.Conventions.Remove<IncludeMetadataConvention>();//防止黑幕交易 要不然每次都要訪問 EdmMetadata這個表
        }
    }
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章