This article shows how to access MySQL data using an Entity Framework code-first approach. Entity Framework 6 is available in .NET 4.5 and above. Show
Entity Framework is an object-relational mapping framework that can be used to work with data as objects. While you can run the ADO.NET Entity Data Model wizard in Visual Studio to handle generating the Entity Model, this approach, the model-first approach, can put you at a disadvantage if there are changes in your data source or if you want more control over how the entities operate. In this article you will complete the code-first approach to accessing MySQL data using the CData ADO.NET Provider.
Entity Framework Extensions EF6 - MySql ProviderMySQL is an open-source relational database management system (RDBMS) and it is known for its quick processing, proven reliability, ease and flexibility of use.
Install EFELet's create a new application using the Console App (.NET Framework) template and install Z.EntityFramework.Extensions. Entity Framework Extensions (EFE) library is available as a nuget package and you can install it using Nuget Package Manager. In the Package Manager Console window, enter the following command. PM> Install-Package Z.EntityFramework.Extensions You can also install EFE by right-clicking on your project in Solution Explorer and select Manage Nuget Packages.... Search for Z.EntityFramework.Extensions and install the latest version by pressing the install button. Register EF ProviderEF providers can be registered
using either code-based configuration or in the application's config file. Install the MySql.Data.Entity NuGet package to add this reference automatically within PM> Install-Package MySql.Data.Entity Let's open the <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- For more information on Entity Framework configuration, visit http: <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <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.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/> </providers> </entityFramework> </configuration> Note that often if the EF provider is installed from NuGet, then the NuGet package will automatically add this registration to the config file.
ConfigurationSet the new
[DbConfigurationType(typeof(MySqlEFConfiguration))]
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
You are now ready to start your application. Create Data ModelModel is a collection of classes to interact with the database.
To create a data model for our application, we will start with the following two entities. public class Author { public int AuthorId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public List<Book> Books { get; set; } } public class Book { public int BookId { get; set; } public string Title { get; set; } public Author Author { get; set; } } There's a one-to-many relationship between Create Database ContextThe database context class provides the main functionality to coordinate Entity Framework with a given data model.
So, let's add a new public class BookStore : DbContext { public BookStore() : base("BookStoreContext") { } public DbSet<Author> Authors { get; set; } public DbSet<Book> Books { get; set; } } This code creates a Setup DatabaseThe name of the connection string is passed into the constructor of the context class. public BookStore() : base("BookStoreContext") { } So, let's open the application <connectionStrings> <add name="BookStoreContext" connectionString="server=localhost;database=BookStoreDb;uid=root;password=;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> The above connection string specifies that Entity Framework will use a Now, we are done with the required classes, so let's add some authors and books records to the database and then retrieve it. using (var context = new BookStore()) { context.Database.Delete(); var authors = new List<Author> { new Author { FirstName ="Carson", LastName ="Alexander", BirthDate = DateTime.Parse("1985-09-01"), Books = new List<Book>() { new Book { Title = "Introduction to Machine Learning"}, new Book { Title = "Advanced Topics in Machine Learning"}, new Book { Title = "Introduction to Computing"} } }, new Author { FirstName ="Meredith", LastName ="Alonso", BirthDate = DateTime.Parse("1970-09-01"), Books = new List<Book>() { new Book { Title = "Introduction to Microeconomics"} } }, new Author { FirstName ="Arturo", LastName ="Anand", BirthDate = DateTime.Parse("1963-09-01"), Books = new List<Book>() { new Book { Title = "Calculus I"}, new Book { Title = "Calculus II"} } } }; context.BulkInsert(authors, options => options.IncludeGraph = true ); } using (var context = new BookStore()) { var list = context.Authors .Include(a => a.Books) .ToList(); foreach (var author in list) { Console.WriteLine(author.FirstName + " " + author.LastName); foreach (var book in author.Books) { Console.WriteLine("\t" + book.Title); } } } If you run the application, you will see that authors and books are successfully inserted into the database. How do I create a connection string in Entity Framework?Use Code First with connection by convention.. Use Code First with connection by convention and specified database name.. Use Code First with connection string in app.config/web.config file.. Database/Model First with connection string in app.config/web.config file.. Other DbContext constructor options.. How do I create a connection string in MySQL?Driver={mySQL};Server=myServerAddress;Port=3306;Option=131072;Stmt=;Database=myDataBase;User=myUsername;Password=myPassword; The driver defaults to port value 3306, if not specified in the connection string, as 3306 is the default port for MySQL.
Can you use Entity Framework with MySQL?MySQL Connector/NET integrates support for Entity Framework 6 (EF6), which now includes support for cross-platform application deployment with the EF 6.4 version.
How does Entity Framework connect to SQL database?You can test the API directly with a tool such as Postman or hook it up with an example Angular or React app available.. Starting in debug mode. ... . Add SQL Server database provider from NuGet. ... . Add connection string to app settings. ... . Update Data Context to Use SQL Server. ... . Install dotnet ef tools.. |