EntityFramework简单例子详解编程语言

@(编程)

这个例子是用vs2013连接mysql数据库。

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(); 
        } 
    } 
} 
 

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

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/20961.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论