自学内容网 自学内容网

C# EF 使用

WPF EF MySQL

- - -版本
.NET Framework4.7.2
EntityFramework6.5.1
MySql.Data.EntityFramework9.1.0
  • 创建数据库 cc
  • App.config
<connectionStrings>
    <add name="MyDbContext" providerName="MySql.Data.MySqlClient" connectionString="server=127.0.0.1;port=3306;database=cc;user=root;password=123456;persistsecurityinfo = True;Character Set=utf8;" />
</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=9.1.0.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
    </DbProviderFactories>
</system.data>
  • 测试
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();


        try
        {
            using (var context = new MyDbContext())
            { 

                // 查询
                var entities = context.MyEntities.Where(e => e.Name == "example").ToList();

                // 添加
                var newEntity = new MyEntity { Name = "new example" };
                context.MyEntities.Add(newEntity);
                context.SaveChanges();

                // 更新
                //var existingEntity = context.MyEntities.Find(newEntity.Id);
                //existingEntity.Name = "updated example";
                //context.SaveChanges();

                // 删除
                // context.MyEntities.Remove(existingEntity);
                //context.SaveChanges();
            }
        }catch (Exception ex)
        {
            var d = "";
        }



    }
}


[DbConfigurationType(typeof(MySql.Data.EntityFramework.MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
    public MyDbContext() : base("name=MyDbContext")
    { 
    } 

    public DbSet<MyEntity> MyEntities { get; set; }
}

[Table("my_table")]
public class MyEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}
  • 打开 NuGet 包管理器控制台
Enable-Migrations -Force # 会在跟目录生成 Migrations\Configuration.cs
AutomaticMigrationsEnabled = true;  # Configuration.cs 中修改
update-database -Force# 迁移
Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConnectionStringName <String>] [-Force] [<CommonParameters>]
ContextTypeName:项目继承自DBContext的类名字。
EnableAutomaticMigrations:开启自动迁移。
ProjectName:存放DBContext类的项目名称。
StartUpProjectName:解决方案中启动项目的名称,作用是调用该项目下的连接字符串。
ConnectionStringName:连接字符串名称

Enable-Migrations -ContextTypeName "WpfApp2.MyDbContext" -ProjectName "WpfApp2" -StartUpProjectName "WpfApp2" -ConnectionStringName "MyDbContext" -Verbose -Force
update-database  -ProjectName "WpfApp2" -StartUpProjectName "WpfApp2" -ConnectionStringName "MyDbContext"  -Verbose -Force

WPF EF SQLServer

- - -版本
.NET Framework4.7.2
EntityFramework6.5.1
  • 创建数据库 cc
  • App.config
<connectionStrings>
    <add name="MyDbContext" providerName="System.Data.SqlClient" connectionString="data source=LAPTOP-EGHJ2RO7;initial catalog=t1;user id=sa;password=1234567;connection timeout=5" />
</connectionStrings>
  • 测试
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();


        try
        {
            using (var context = new MyDbContext())
            { 

                // 查询
                var entities = context.MyEntities.Where(e => e.Name == "example").ToList();

                // 添加
                var newEntity = new MyEntity { Name = "new example" };
                context.MyEntities.Add(newEntity);
                context.SaveChanges();

                // 更新
                //var existingEntity = context.MyEntities.Find(newEntity.Id);
                //existingEntity.Name = "updated example";
                //context.SaveChanges();

                // 删除
                // context.MyEntities.Remove(existingEntity);
                //context.SaveChanges();
            }
        }catch (Exception ex)
        {
            var d = "";
        }



    }
}

public class MyDbContext : DbContext
{
    public MyDbContext() : base("name=MyDbContext")
    { 
    } 

    public DbSet<MyEntity> MyEntities { get; set; }
}

[Table("my_table")]
public class MyEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}
  • 打开 NuGet 包管理器控制台
Enable-Migrations -Force # 会在跟目录生成 Migrations\Configuration.cs
AutomaticMigrationsEnabled = true;  # Configuration.cs 中修改
update-database -Force# 迁移
Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConnectionStringName <String>] [-Force] [<CommonParameters>]
ContextTypeName:项目继承自DBContext的类名字。
EnableAutomaticMigrations:开启自动迁移。
ProjectName:存放DBContext类的项目名称。
StartUpProjectName:解决方案中启动项目的名称,作用是调用该项目下的连接字符串。
ConnectionStringName:连接字符串名称

Enable-Migrations -ContextTypeName "WpfApp2.MyDbContext" -ProjectName "WpfApp2" -StartUpProjectName "WpfApp2" -ConnectionStringName "MyDbContext" -Verbose -Force
update-database  -ProjectName "WpfApp2" -StartUpProjectName "WpfApp2" -ConnectionStringName "MyDbContext"  -Verbose -Force

原文地址:https://blog.csdn.net/weixin_45381071/article/details/143480276

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!