MYSQL与Entity Framework

因为在练习c#时用到了Entity Framework而刚好VS2015里面没有默认配置的localdb与sql server,于是决定采用MYSQL数据库。codefirst的代码采用https://msdn.microsoft.com/zh-cn/data/jj193542,大致流程如下:

1、创建项目

  • “文件”->“新建”->“项目…”
  • 从左侧菜单中选择“Windows”和“控制台应用程序”
  • 输入 CodeFirstNewDatabaseSample 作为名称
  • 选择“确定”

2、添加NuGet 程序包

  • “项目”–>“管理 NuGet 程序包…”
  • 注意:如果没有“管理 NuGet 程序包…”选项,则应安装 最新版本的 NuGet
  • 选择“联机”选项卡
  • 选择“EntityFramework”,”MySql.Data.Entity” 程序包安装

3、插入代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace CodeFirstNewDatabaseSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                // Create and save a new Blog 
                Console.Write("Enter a name for a new Blog: ");
                var name = Console.ReadLine();

                var blog = new Blog { Name = name };
                db.Blogs.Add(blog);
                db.SaveChanges();

                // Display all Blogs from the database 
                var query = from b in db.Blogs
                            orderby b.Name
                            select b;

                Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public BloggingContext() : base("BloggingContext") { }
        public DbSet Blogs { get; set; }
        public DbSet Posts { get; set; }
    }
}

4、配置app.config

在configuration标签内最下面加入

  <connectionStrings>
    <add name="BloggingContext" connectionString="Server=127.0.0.1;Database=BloggingContext;Uid=root;Pwd=123456;"   providerName="MySql.Data.MySqlClient" />
  connectionStrings>

注意这里的name要与上方代码片中base相对应。

你可能感兴趣的:(MYSQL与Entity Framework)