EF6中CodeFirst使用MySQL

来源:互联网 发布:lca类似算法 编辑:程序博客网 时间:2024/05/22 04:48

Program.cs代码:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MySQLuse{    class Program    {        static void Main(string[] args)        {            using (var entity = new ExampleDBContext())            {                //查询,删除                List<User> list = entity.Users.ToList<User>();                for (int i = 0; i < list.Count; i++)                {                    entity.Entry(list[i]).State = EntityState.Deleted;                    Console.WriteLine(list[i].Id);                    entity.SaveChanges();                }                //增加                 User user = new User() { Name = "雷克斯 阿帕奇", Email = "wutqqqqqq@gmail.com" };                user = entity.Users.Add(user);                entity.SaveChanges();                Console.ReadKey();            }        }    }}

ExampleDBContext.cs

using MySql.Data.Entity;using System;using System.Collections.Generic;using System.Data.Common;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MySQLuse{    [DbConfigurationType(typeof(MySqlEFConfiguration))]    public class ExampleDBContext : DbContext    {        public ExampleDBContext() : base("name=MyContext")        {            //Configuration.ProxyCreationEnabled = true;            //Configuration.LazyLoadingEnabled = true;            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ExampleDBContext, Migrations.Configuration>());        }        public ExampleDBContext(DbConnection existingConnection, bool contextOwnsConnection)      : base(existingConnection, contextOwnsConnection)        {            Configuration.ProxyCreationEnabled = true;            Configuration.LazyLoadingEnabled = true;            Configuration.AutoDetectChangesEnabled = true;        }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            base.OnModelCreating(modelBuilder);            //modelBuilder.Entity<User>();        }        public DbSet<User> Users { get; set; }    }    public class User    {        public int Id { get; set; }        public String Name { get; set; }        public String Email { get; set; }    }}

Configuration.cs

namespace MySQLuse.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    internal sealed class Configuration : DbMigrationsConfiguration<EF6CodeFirstMySQL.ExampleDBContext>    {        public Configuration()        {            AutomaticMigrationsEnabled = false;            //AutomaticMigrationDataLossAllowed = true;        }        protected override void Seed(EF6CodeFirstMySQL.ExampleDBContext context)        {            //  迁移到最新版本后将调用此方法            // 您可以使用 DbSet<T>.AddOrUpdate() 辅助扩展方法来避免创建重复的种子数据。 例如。             //    context.People.AddOrUpdate(            //      p => p.FullName,            //      new Person { FullName = "Andrew Peters" },            //      new Person { FullName = "Brice Lambson" },            //      new Person { FullName = "Rowan Miller" }            //    );            //        }    }}

App.config

<?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"/>  </configSections>  <connectionStrings>    <add name="ExampleStr" connectionString=" data source=(host);initial catalog=Example;persist security info=True;user id=user;password=pwd;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>    <add name="MyContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=mvcexample;uid=root;password=123456"/>  </connectionStrings>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>  </startup>  <entityFramework>    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>    <providers>      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>    </providers>  </entityFramework>  <system.data>    <DbProviderFactories>      <remove invariant="MySql.Data.MySqlClient"/>      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>    </DbProviderFactories>  </system.data></configuration>

运行结果如图:

这里写图片描述

阅读全文
0 0