如果使用EntityFramework6链接Mysql
web.config文件中加入这些:
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6"> <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> <connectionStrings> <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=MyBook;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" /> </connectionStrings>
新建User类
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace CodeFirstMysql { public class User { public int Id { get; set; } public string UserName { get; set; } //默认string映射到mysql里是longtext类型的,加长度之后就变成varchar了
[MaxLength(30)] public string PassWord { get; set; } } }
新建MyContext类,此类继承DbContext
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; namespace CodeFirstMysql { public class MyContext : DbContext { public MyContext() : base("name=MyContext")//web.config中connectionstring的名字 { } public DbSet<User> Users { get; set; } } }
Default.aspx.cs文件内容:
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CodeFirstMysql { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { InitData(); } private void InitData() { Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>()); var context = new MyContext();
//插入一行值 context.Users.Add(new User {UserName = "EF6-MySQL-Code-First"}); context.SaveChanges(); } } }
运行之后看效果:
show tables:
desc table:
表中数据:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
2015-07-13 产品经理如何赢得开发人员的尊重和支持?-摘自infoq
2015-07-13 Microsoft TFS 如何显示在Windows 的上下文菜单中
2010-07-13 反射----重载的方法
2009-07-13 下载文件(类似与<A href>)