当前位置:网站首页>MySQL-- Entity Framework Code First(EF Code First)
MySQL-- Entity Framework Code First(EF Code First)
2022-06-30 09:26:00 【LongtengGensSupreme】
Use MySQL and Entity Framework Code First(EF Code First) Create database .
1、 New console project ConsoleApp1, Usage management NuGet Program , add to MySql.Data.Entities,MySql.Data.Entities( Automatically install dependencies MySql.Data,EntityFramework)
2、 After installing the package, see the following :


3、 stay app.config Add the following , without app.config, Create one manually .
<?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>
<connectionStrings>
<!-- add to mysql Connection string -->
<add name="conn" connectionString="server=localhost;port=3306;uid=root;[email protected];database=testdb;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<!-- add to Asp.Net EF visit Mysql database , Otherwise, the report will be wrong :No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'.-->
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</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.8.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<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>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.8.8.0" newVersion="6.8.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>Be careful : Above the red mark , add to mysql Connection string as well as add to Asp.Net EF visit Mysql database , Otherwise, the report will be wrong :No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'
4、 Add data context MyDBContext, The code is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Text;
namespace ConsoleApp1
{
public class MyDBContext : DbContext
{
public DbSet<Testmy> Testmies { get; set; }
public MyDBContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Testmy>().ToTable($"tbl-{typeof(Testmy)}")
.HasKey(a => a.Id)
.Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
public class Testmy
{
public int Id { get; set; }
public string Name { get; set; }
}
}5、Program Add the following code :
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class Program
{
static void Main(string[] args)
{
using (var db = new MyDBContext("name=conn"))
{
var isCreate = db.Database.CreateIfNotExists();
for (int i = 0; i < 10; i++)
{
db.Testmies.Add(new Testmy { Name = $"{i}-- name " });
}
db.SaveChanges();
}
Console.WriteLine(" Create success ");
Console.Read();
}
}
}6、 Running results :

边栏推荐
- ES6 learning path (II) let & const
- Advanced technology management -- how managers design and build echelons
- Esp32 (6): Bluetooth and WiFi functions for function development
- Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
- Interviewer: do you understand the principle of recyclerview layout animation?
- Treatment process record of Union Medical College Hospital (Dongdan hospital area)
- Deep understanding of kotlin collaboration context coroutinecontext
- Do you want the dialog box that pops up from the click?
- Flink SQL custom connector
- Applet learning path 2 - event binding
猜你喜欢

Handwriting sorter component

Based on svelte3 X desktop UI component library svelte UI

桂林 穩健醫療收購桂林乳膠100%股權 填補乳膠產品線空白

Anchorgenerator for mmdet line by line interpretation

C accesses mongodb and performs CRUD operations

Dart asynchronous task

Flutter 0001, environment configuration

Flink SQL custom connector

Talking about kotlin process exception handling mechanism

Do you want the dialog box that pops up from the click?
随机推荐
The elegant combination of walle and Jianbao
Do you want the dialog box that pops up from the click?
Opencv learning notes -day1 (image reading display imread, imshow, namedwindow)
Deep Learning with Pytorch- A 60 Minute Blitz
Coredata acquisition in swift sorting, ascending, descending
QT connection to Shentong database
Influencing factors of echo cancellation for smart speakers
Esp32 things (V): analysis of common API of esp32 of Swiss Army knife
What are the SQL add / delete / modify queries?
快应用中实现自定义抽屉组件
Using appbarlayout to realize secondary ceiling function
Tutorial for beginners of small programs day01
Esp32 things (I): Preface
Application of hongruan face recognition
Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function
Interpretation of orientedrcnn papers
POJ 1753 flip game (DFS 𞓜 bit operation)
Torchvision loads the weight of RESNET except the full connection layer
ES6 learning road 5 symbol
Pipe pipe --namedpipe and anonymouspipe