@(编程)

1. NuGet安装EF和mysql

2. 对象


namespace EFDemo
{
class Student
{
public string Id { get; set; } public string Name { get; set; } }
}

3. Context

using System.Data.Entity;

namespace EFDemo
{
class DefaultContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
}

4. 配置文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<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.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider>
</providers>
</entityFramework>
<connectionStrings>
<add name="DefaultContext" providerName="MySql.Data.MySqlClient" connectionString="Server=127.0.0.1; database=test10; uid=root; password=password;"/>
</connectionStrings>
<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.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>

5. 调用程序

using MySql.Data.Entity;
using System;
using System.Data.Entity; namespace EFDemo
{
class Program
{
static void Main(string[] args)
{
DbConfiguration.SetConfiguration(new MySqlEFConfiguration());
var context = new DefaultContext();
Student item = new Student();
item.Id = Guid.NewGuid().ToString();
item.Name = "keke";
context.Students.Add(item);
context.SaveChanges();
}
}
}

程序执行后,自动创建数据库与表,非常方便。

05-04 06:33