ASP.NET: Setup a MVC5 website with MySQL, Entity Framework 6 Code-First and VS2013
The new features available in EF6 allow any developer to build a simple DB-powered website with very few lines of code. There are many tutorials explaining how to do that with SQL Express available on the web, but those who want (or are forced) to use MySQL will most likely find a quite smaller amount of literature. I wrote this simple guide for those who asked me to summarize all the required steps to build a MySQL-powered MV5 website using Visual Studio 2013 and Entity Framework 6. For the first steps I’m gonna quote the old good Getting started with Entity Framework 6 Code First using MVC5 available on www.asp.net website, which also holds the credits for the images I used.
Let’s start with a list of everything we’re gonna need (and their free download links):
- Visual Studio 2013, downloadable here (free 90-days trial edition).
- .NET Framework 4.5 or higher, downloadable here.
- Entity Framework 6 or higher, available on NuGet platform.
- MySQL Server 5.6 or higher, downloadable from the official site, or a free or paid access to a remotely-hosted MySQL database service of your choice.
- MySQL Connector.NET 6.9.4 or higher, downloadable from the official site or using NuGet.
Step 1. Creating a new Web Application
Let’s start Visual Studio 2013 and create a new C# project just like that:
In the following screen we’re gonna choose the MVC template, then we’re click to the Change Authentication… button where we can choose if we want to enable authentication mechanism or not. The answer here depends on the features we need to have in the website we’re building: for this example we do not need any authentication system, so we can choose No Authentication.
The next steps are kinda obvious, we just have to click a couple OKs to end the web application creation phase.
Step 2. Installing the Entity Framework
From the Tools menu, select Library Package Manager and then Package Manager Console. Insert the following command:
> Install-Package EntityFramework
NuGet will automatically download and install the most recent version of the Entity Framework (currently 6.1.1). As soon as the tasks is completed we can start creating our Entities following the code-first approach.
Step 3. Creating the Entity Classes
It’s worth to mention that an Entity isn’t anything more than a class designed to hold all the relevant fields about a single element (i.e. row) of our Database. That’s why before we start creating Entities we definitely need to have a decent idea about what we need and, most importantly, which kind of relationship our elements are gonna have. For this example let’s just flush out an evergreen classic: The Student-Enrollment-Course archive. Here’s what we’re gonna have:
- a list of Students
- signing up to zero-or-more Enrollments
- related to zero-or more Courses
In order to build such a model we need to open the /Models/ folder (creating it if it doesn’t exists) and add the following three classes:
using System;
using System.Collections.Generic; namespace MyApplication.Models
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
using System; namespace MyApplication.Models
{
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
[crayon-567743939cb3f039488039 inline="true" ]
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema; namespace MyApplication.Models
{
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
Step 4. Setting up the Database Context
The main class who handles and keeps track of the various Entity Framework operations is known as Database Context. It can be created by adding a new class, deriving it from System.Data.Entity.DbContext and inserting some properties for all the Entities we just created, who will populate the Data Model. Let’s move to the /DAL/ folder (for Data-Access-Layer), creating it if it doesn’t exist already, and add the following two classes:
using MyApplication.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions; namespace MyApplication.DAL
{
public class MyDbContext : DbContext
{ public MyDbContext() : base("MyDbContextConnectionString")
{
Database.SetInitializer<MyDbContext>(new MyDbInitializer());
} public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
public class MyDbInitializer : CreateDatabaseIfNotExists<MyDbContext>
{
protected override void Seed(MyDbContext context)
{
// create 3 students to seed the database
context.Students.Add(new Student { ID = , FirstName = "Mark", LastName = "Richards", EnrollmentDate = DateTime.Now });
context.Students.Add(new Student { ID = , FirstName = "Paula", LastName = "Allen", EnrollmentDate = DateTime.Now });
context.Students.Add(new Student { ID = , FirstName = "Tom", LastName = "Hoover", EnrollmentDate = DateTime.Now });
base.Seed(context);
}
}
We can see that the MyDbContext.cs class contains a DbSet for each Entity we previously created. That’s because in the Entity Framework pattern each DbSet is corresponding to a Database Table, while the Entities are the table records (or rows). We can also see that in the constructor initializer we’re instantiating an object of type MyDbInitializer, which is defined in the following class: we need this object to initialize the database the first time we launch the application and also to insert some sample record in the newly created Student table. We can derive the MyDbInitializer from a number of initialization base class made available by the framework, such as:
- CreateDatabaseIfNotExists: This is the default initialized: as the name suggests, it creates the database if it doesn’t exist already. It’s worth to say that if the DB is already present and it’s Model differs from the one specified by the Entities, this initializer will throw an exception. This behaviour makes it an optimal choice for the production environments (where you don’t want the DB to be altered by the EF6 automatic tasks) but not-so-great for the development ones (where the Database Model frequently changes).
- DropCreateDatabaseIfModelChanges: This initializer creates a new database, deleting the previous one (if any), everytime the DataModel is changed since the last initialization. It’s worth to mention that a DataModel “change” everytime one or more Entity class is added, removed or modified in any way. This is an ideal behavior for development and testing environments, where we usually want to reset/update the DB every time we need to change the way we want to store data: for these exact same reasons it should never be used in any production environment in order to avoid data-losses (a small change in one Entity class is all it will take to erase all data in the DB).
- DropCreateDatabaseAlways: As the name suggests, this initializer deletes and re-creates the DB on every initialization, i.e. every time the web application will start. This might be good for those development (or testing) environments designed to work with the same, pre-defined amount of data every time: needless to say, it’s far from ideal in any production environment.
Before going on, notice that MyDbContextConnectionString literal referenced by the constructor initializer of our MyDbContext.cs class: this is the connection string we’ll add to our Web.Config during the next step.
Step 5. Connecting to MySQL
To connect our web application to our MySQL database we need the MySQL Connector.NET, which can be downloaded from the official site or using NuGet. All we need to do is to add its libraries to our project and add a valid connection string to our Web.Config file, just like that:
<connectionStrings>
<add name="MyDbContextConnectionString" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;UserId=username;Password=password;database=myDatabase;CharSet=utf8;Persist Security Info=True"/>
</connectionStrings>
Step 6. Running the Application and (auto)creating the Database
If all the previous steps have been properly completed the web application will automatically create the database as soon as an object of type MyDbContext will be instantiated. For example:
private MyDbContext db = new MyDbContext();
You can initialize the object inside a Controller, in a singleton class (or in the Global.asax) as a static property or in other parts of the web application depending on developer needs and/or the choosen design pattern and/or IoC/UoW strategies you might want to adopt. In the upcoming posts I’ll talk more about these techniques, as well as explain other useful EF concepts, capabilities & tools such as Data Migrations and more.
http://www.ryadel.com/en/asp-net-setup-mvc5-website-mysql-entity-framework-6-code-first-vs2013/
ASP.NET: Setup a MVC5 website with MySQL, Entity Framework 6 Code-First and VS2013的更多相关文章
- 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表
创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添 ...
- MVC2、MVC3、MVC4、MVC5之间的区别 以及Entity Framework 6 Code First using MVC 5官方介绍教程
现在MVC的技术日趋成熟,面对着不同版本的MVC大家不免有所迷惑 -- 它们之间有什么不同呢?下面我把我搜集的信息汇总一下,以便大家能更好的认识不同版本MVC的功能,也便于自己查阅. View Eng ...
- 关于MySql entity framework 6 执行like查询问题解决方案
原文:关于MySql entity framework 6 执行like查询问题解决方案 本人不善于言辞,直接开门见山 环境:EF6.0.0.0+MySQL Server5.6+MySqlConnec ...
- [Entity Framework] MySQL @ Entity Framework 6
原文 [Entity Framework] MySQL @ Entity Framework 6 要让MySQL能够用EF6,我花了一点时间,在此记录一下 安装元件 在设定档加入Provider 安装 ...
- Entity Framework 6 Code First 系列:无需修改实体和配置-在MySql中使用和SqlServer一致的并发控制
无需修改实体和配置,在MySql中使用和SqlServer一致的并发控制.修改RowVersion类型不可取,修改为Timestamp更不可行.Sql Server的RowVersion生成一串唯一的 ...
- ASP.NET Core 快速入门(Razor Pages + Entity Framework Core)
引子 自从 2009 年开始在博客园写文章,这是目前我写的最长的一篇文章了. 前前后后,我总共花了 5 天的时间,每天超过 3 小时不间断写作和代码调试.总共有 8 篇文章,每篇 5~6 个小结,总截 ...
- [ASP.NET MVC 小牛之路]06 - 使用 Entity Framework
在家闲着也是闲着,继续写我的[ASP.NET MVC 小牛之路]系列吧.在该系列的上一篇博文中,在显示书本信息列表的时候,我们是在程序代码中手工造的数据.本文将演示如何在ASP.NET MVC中使用E ...
- 【ASP.NET MVC 学习笔记】- 07 使用 Entity Framework
本文参考:http://www.cnblogs.com/willick/p/3304534.html 1.ORM(Object Relation Mapping)工具,是为了解决“关系数据库”和“面向 ...
- ASP.Net Core项目在Mac上使用Entity Framework Core 2.0进行迁移可能会遇到的一个问题.
在ASP.Net Core 2.0的项目里, 我使用Entity Framework Core 2.0 作为ORM. 有人习惯把数据库的连接字符串写在appSettings.json里面, 有的习惯写 ...
随机推荐
- .Net com组件操作excel(不建议采用Com组件操作excel)
添加"Microsoft Office 12.0 Object Library" com组件 1 using System; using System.Data; using Sy ...
- jquery $.getJSON 注意细节
服务端: var json = "{\"title\": \"Recent Uploads tagged mountrainier\",\" ...
- 自定义 Relam
package org.zln.hello.realm; import org.apache.shiro.authc.*; import org.apache.shiro.realm.Realm; / ...
- 【转】IBatis.Net项目数据库SqlServer迁移至Oracle
转自:http://www.2cto.com/database/201312/265514.html 最近完成了一个(IBatis.Net+MVC)项目的数据库+代码迁移工作,可把我折腾得~~~ IB ...
- Linux相关——关于文件调用
本文主要记录几个常见文件调用(表示为了造数据试了n种方法,,,发现了一些神奇的东西,会在下面一一说明. 首先在程序中我们可以打开和关闭程序. 常见的freopen用法简单,但是只能使用一次,如果在程序 ...
- BZOJ2819 Nim 【dfn序 + lca + 博弈论】
题目 著名游戏设计师vfleaking,最近迷上了Nim.普通的Nim游戏为:两个人进行游戏,N堆石子,每回合可以取其中某一堆的任意多个,可以取完,但不可以不取.谁不能取谁输.这个游戏是有必胜策略的. ...
- [SDOI2010]星际竞速——费用流
类似于最短路的网络流,而且还要保证每个点经过一次,拆点就比较方便了. 连边怎么连?要保证最大流是n(每个点经过一次)还要能从直接跳转 将每个点拆点.源点向每个点的入点连一条容量为1费用为0的边.源点向 ...
- [NOIP2009]靶形数独 深搜+枝杈优化
这道题,又是一位玄学搜索...... 我是用的蜗牛序搜的(顾名思义,@,这么搜),我正着搜80然后一反转比原来快了几十倍........一下AC....... 我的思路是这样的话我们可以从内到外或者从 ...
- git使用笔记(四)远程操作
By francis_hao Nov 19,2016 以一张图说明远程操作,图片来自参考[2] git clone 从远端主机克隆一个版本库,若省略directory则生成一个和远端同名的版本库 ...
- spring的普通类中如何取session和request对像
在使用spring时,经常需要在普通类中获取session,request等对像. 比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts ...