Connect to MYSQL using Entityframeworkcore

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.