If you want to work with MySql database using an Entity Framework project that uses MySql.Data.Entity (the latest version is 6.10.X) and MySql.Data (latest version is 8.0.X), those version numbers should match. You should use MySql.Data.EntityFramework package with MySql.Data version 8.0 and later versions, and the MySql.Data.Entity package with versions 6.10 and earlier versions.
Create a new project using Visual Studio. Go to Web => ASP.NET Web Application => MVC Project Template.
Authentication => No Authentication
Open NuGet Package Manager Console
Tools => NuGet Package Manager => Package Manager Console
- Enter Command => Install MySql.Data => Press Enter (You have to connect to internet)
- Enter Command => Install MySql.Data.EntityFramework (You have to connect to internet)
After installing packages, go to the web config file and add a connection string with the name DefaultConnection. Make sure you have installed MySql server on your local computer or set connection string for remote server.
- <addname="DefaultConnection"connectionString="server=localhost;userid=root;password=root;database=testDb;persistsecurityinfo=true"providerName="MySql.Data.MySqlClient" />
Replace the username password as per your environment.
Add a new class in Models folder.
- [DbConfigurationType(typeof(MySqlEFConfiguration))]
- public class ApplicationDbContext: DbContext {
- public DbSet Products {
- get;
- set;
- }
- public ApplicationDbContext(): base("DefaultConnection")
- {}
- }
Add a new class file in Models folder.
- public class Product {
- public int Id {
- get;
- set;
- }
- [Required]
- [StringLength(50)]
- public string Name {
- get;
- set;
- }
- }
Go to Package Manager Console.
Tools => NuGet Package Manager => Package Manager Console
Execute the following commands step by step,
- Enable-migrations
- add-migration InitialModel
- update-database
Done! We have successfully connected the MySql database with Entity Framework.
If you want to check, open the MySQL workbench and check there is a database created with name testDb which has products table also.
Add a new API Controller and add the following code to it. Please add the following lines to the Global.asax.cs file.
- GlobalConfiguration.Configure(WebApiConfig.Register);
- public class ProductsController: ApiController {
- private static ApplicationDbContext _context;
- public ProductsController() {
- _context = new ApplicationDbContext();
- }
- protected override void Dispose(bool disposing) {
- _context.Dispose();
- }
-
- public IEnumerable < Product > GetProducts() {
- return _context.Products.ToList();
- }
-
- public Product GetProducts(int id) {
- return _context.Products.SingleOrDefault(p => p.Id == id);
- }
- }
Build your application and test your API by going through the following URL.
http:localhost:port/api/products (replace port no with your application port)
You can also test your API using postman or any other test client.