What is Entity Framework
Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.
转自msdn https://msdn.microsoft.com/en-us/data/ef.aspx?f=255&MSPPError=-2147217396
Entity Framework可以用来操作数据库
首先我们要从nuget获取EF
在控制台管理器中输入 Install-Package EntityFramework 即可安装最新版的EF
EF默认连接local db这里我们需要他支持mysql
首先我们需要从nuget获取Mysql.Data 和Mysql.Data.Entity
然后创建类
public class MysqlDbConfiguration : DbConfiguration
{
public MysqlDbConfiguration()
{
SetHistoryContext(
"MySql.Data.MySqlClient", (conn, schema) => new MysqlHistoryContext(conn, schema));
}
}
public class MysqlHistoryContext : HistoryContext
{
public MysqlHistoryContext(
DbConnection existingConnection,
string defaultSchema)
: base(existingConnection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}
public class ExtMySqlMigrationSqlGenerator : MySqlMigrationSqlGenerator
{
protected override System.Data.Entity.Migrations.Sql.MigrationStatement Generate(System.Data.Entity.Migrations.Model.AddForeignKeyOperation op)
{
if (op.Name.Length > 64)
op.Name = "FK__" + op.Name.Substring(op.Name.Length - 60, 60);
var ret = base.Generate(op);
return ret;
}
protected override System.Data.Entity.Migrations.Sql.MigrationStatement Generate(System.Data.Entity.Migrations.Model.RenameTableOperation op)
{
var str = base.Generate(op);
str.Sql = str.Sql.Replace("dbo.", "");
return str;
}
protected override System.Data.Entity.Migrations.Sql.MigrationStatement Generate(System.Data.Entity.Migrations.Model.DropForeignKeyOperation op)
{
var str = base.Generate(op);
str.Sql = str.Sql.Replace("dbo.", "");
return str;
}
protected override System.Data.Entity.Migrations.Sql.MigrationStatement Generate(System.Data.Entity.Migrations.Model.DropPrimaryKeyOperation op)
{
var str = base.Generate(op);
str.Sql = str.Sql.Replace("dbo.", "");
return str;
}
protected override System.Data.Entity.Migrations.Sql.MigrationStatement Generate(System.Data.Entity.Migrations.Model.AddPrimaryKeyOperation op)
{
var str = base.Generate(op);
str.Sql = str.Sql.Replace("dbo.", "");
return str;
}
}
这样,EF就可以支持mysql数据库了,因为微软的 SQL server实在是太臃肿了,所以我们选择了轻便的mysql。 这里我们使用的是MariaDb,是mysql的作者开发的开源数据库,跟mysql一毛一样,而且不用担心mysql被收购产生的其他影响。
EF是用来与数据库进行交互的,我们可以通过EF轻松的与数据库进行交互,而且在asp.net MVC的框架中,默认是安装EF的,可见EF还是比较受欢迎的,下一章将写怎么使用EF
活学活用,have fun。
么么么么哒