The previous article describes how to use dapper to connect to MySQL under Dotnetcore, which is described here using the Entityframeworkcore connection to MySQL.
To create a new console project, install the following two NuGet packages:
install-Packagemicrosoft.entityframeworkcoreinstall-package mysql.data.entityframeworkcore-pre
Define two classes and context:
Public classBlogcontext:dbcontext {protected Override voidonconfiguring (Dbcontextoptionsbuilder optionsbuilder) {optionsbuilder.usemysql ("Server=10.255.19.111;database=mydb;uid=root;pwd=yourpassword;"); } PublicDbset<blog> Blog {Get;Set; } PublicDbset<user> User {Get;Set; } } Public classBlog { Public intId {Get;Set; } Public stringURL {Get;Set; } } [Table ("User")] Public classUser { Public intId {Get;Set; } Public stringName {Get;Set; } PublicDateTime Createtime {Get;Set; } }
Test in Main:
using (varnew blogcontext ()) { //User user = new user () {Name = "Herry", createtime = DateTime.Now}; // context. User.add (user); New " http://mysite.com " }; CONTEXT.BLOG.ADD (blog); Context. SaveChanges (); }
Here's what to note:
Public Get set; }
If MySQL table name blog is lowercase, this is to be defined as the table name exactly the same, otherwise it will be error, when connecting MSSQLServer when the table name is blogs, then you can define as follows:
Public Get set; }
If the table name is a blog, you can use annotation properties:
[Table ("Blog")] Public class Blog { publicintgetset;} Public string Get Set ; } }
This annotation attribute does not work in MySQL, so annotations on user are not useful.
Connect to MYSQL using Entityframeworkcore