1.概要
EF 简单实验,使用mode
2.代码
using MySql.Data.EntityFramework;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
namespace EF简单实验_模型
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("EF简单实践");
using (DBContentMy db = new DBContentMy())
{
Tb1 tb1 = new Tb1();
tb1.v1 = 1;
db.Tb1s.Add(tb1);
db.SaveChanges();
}
using (DBContentMy db = new DBContentMy())
{
foreach (Tb1 tb1 in db.Tb1s.ToList()) {
Console.WriteLine(tb1.id+" "+tb1.v1);
}
}
Console.ReadKey();
}
}
[Table("Tb1")]
class Tb1
{
public int id { set; get; }
public int v1 { set; get; }
}
[DbConfigurationType(typeof(MySqlEFConfiguration))]
class DBContentMy : DbContext
{
public DBContentMy() : base("DbConnStr")
{
Database.SetInitializer<DBContentMy>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Tb1> Tb1s { set; get; }
}
}
2.2 配文件
<?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.7.1" />
</startup>
<connectionStrings>
<add name="DbConnStr" connectionString="Data Source=localhost;port=3306;Initial Catalog=db;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<entityFramework>
<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.EntityFramework, Version=8.0.26.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider></providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
3.运行结果

4.其他
4.1 创建数据库脚本
CREATE TABLE `tb1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`v1` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
4.2 nuget配置(选择这一个,其他的关联插件会自动下载)

这篇博客展示了如何使用Entity Framework与MySql.Data.EntityFramework库进行简单的数据库操作。通过创建一个模型类Tb1,定义数据库上下文DBContentMy,并配置连接字符串,实现了数据的插入和查询。在配置文件中指定了MySql数据库的连接信息,并在代码中通过SaveChanges()方法保存了数据。运行结果成功显示了插入的数据。
788

被折叠的 条评论
为什么被折叠?



