ef 框架 mysql_EF+Mysql+DDD框架搭建(一)——code first准备

准备mysql for vs工具

mysql-connector-net-6.8.3.msi 网盘地址:http://pan.baidu.com/s/1jHDWINk

mysql-for-visualstudio-1.1.4.msi 网盘地址:http://pan.baidu.com/s/1eSwemno

打开VS工具-》库程序包管理器-》程序包管理器控制平台

安装EF和mysql依赖包

1.PM>  Install-Package MySql.Data.Entity -Version 6.9.8

2.PM>  Install-Package EntityFramework

安装完成之后配置数据库连接字符串connectionStrings

在web项目中model文件夹下创建Users实体和MyUserContext上下文对象

Users实体类

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Web;namespacePMS.Web.Models

{///

///users实体对象///

public classUsers

{public int Id { get; set; }public string UserName { get; set; }//默认string映射到mysql里是longtext类型的,加长度之后就变成varchar了

[MaxLength(30)]public string PassWord { get; set; }

}

}

MyUserContext上下文对象

usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Web;namespacePMS.Web.Models

{

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]public classMyUserContext : DbContext

{publicMyUserContext()

:base("name=MyContext")//web.config中connectionstring的名字

{

}public DbSet Users { get; set; }

}

}

HomeController.cs

usingPMS.Web.Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespacePMS.Web.Controllers

{public classHomeController : Controller

{publicActionResult Index()

{

InitData();returnView();

}private voidInitData()

{

Database.SetInitializer(new DropCreateDatabaseAlways());var context = newMyUserContext();//插入一行值

context.Users.Add(new Users { UserName = "EF6-MySQL-Code-First"});

context.SaveChanges();

}

}

}

运行项目,如果出现“无法检查模型兼容性,因为数据库不包含模型元数据。只能检查使用 Code First 或 Code First 迁移创建的数据库的模型兼容性。”

在Visual Studio中对其进行迁移

1.PM>Enable-Migrations

2.配置Configuration的AutomaticMigrationsEnabled属性

namespacePMS.Web.Migrations

{usingSystem;usingSystem.Data.Entity;usingSystem.Data.Entity.Migrations;usingSystem.Linq;internal sealed class Configuration : DbMigrationsConfiguration{publicConfiguration()

{

AutomaticMigrationsEnabled= true;

}protected override voidSeed(PMS.Web.Models.MyUserContext context)

{//This method will be called after migrating to the latest version.//You can use the DbSet.AddOrUpdate() helper extension method//to avoid creating duplicate seed data. E.g.//

//context.People.AddOrUpdate(//p => p.FullName,//new Person { FullName = "Andrew Peters" },//new Person { FullName = "Brice Lambson" },//new Person { FullName = "Rowan Miller" }//);//}

}

}

3.PM>Update-Database-Force

重新运行项目。此时已经可以正常运行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值