在VisualStadio2015上使用EF6.0建立MySql数据库
1.新建工程
2.建立類的文件夾DAL
3.建立相關(guān)類
【Student類】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ETTest3
{
public class Student
{
public int Id { get; set; }
public string LastName { get; set; }
}
}
【School類】
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ETTest3
{
public class SchoolContext : DbContext
{
public SchoolContext() : base("MyContext") { }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
?
4. 引用EF6.0 Mysql.Entity
5.調(diào)整配置文件 app.config
<connectionStrings>
<add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=test;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
?
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider></providers>
</entityFramework>
6 測試建立數(shù)據(jù)庫
try
{
SchoolContext ctx = new SchoolContext();
ctx.Database.Initialize(true);
var o = new Student();
o.Id = 1;
o.LastName = "aa";
ctx.Students.Add(o);
ctx.SaveChanges();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
7.測試成功,打開數(shù)據(jù)庫,可以見到mysql里增加一個(gè)庫test ,里面有一張表student
?
8 數(shù)據(jù)表中的字段發(fā)生變化情況處理
如果變動(dòng)比較小,比如新增或刪除一兩個(gè)字段
先備份好數(shù)據(jù)庫以后?直接進(jìn)行數(shù)據(jù)表操作,將你的數(shù)據(jù)模型和數(shù)據(jù)庫表做上對(duì)應(yīng)就好了,
需要注意的是,項(xiàng)目上線一般需要將DataContext設(shè)置一下
Database.SetInitializer<DataContext>(null);
而不能設(shè)置
Database.SetInitializer<DataContext>(new?DropCreateDatabaseIfModelChanges<DataContext>());或者
Database.SetInitializer<DataContext>(new?DropCreateDatabaseAlways<DataContext>());等等其他方式,
以防意外導(dǎo)致數(shù)據(jù)庫被刪除,重新生成(因?yàn)樽约禾砑幼侄慰赡芘c你的模型映射不一致)
如果改動(dòng)非常大,那么可能就要換另外一種方案了,數(shù)據(jù)遷移,或者自己導(dǎo)入數(shù)據(jù)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/meetweb/p/5572005.html
總結(jié)
以上是生活随笔為你收集整理的在VisualStadio2015上使用EF6.0建立MySql数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到怀孕了什么意思
- 下一篇: MySQL从5.5升级到5.6,TIME