FrameWork使用EfCore数据库映射举例

Microsoft.EntityFrameworkCore新的版本不支持FrameWork框架。

这里举例使用旧版本实现数据存取

首先下载

Microsoft.EntityFrameworkCore 版本控制在2.1.14以下

同样下载Microsoft.EntityFrameworkCore.sqlite

举例时间记录

csharp 复制代码
 public class RunTimeInfo
 {
     [Key]
     public int Id { get; set; }

     [Description("统计小时")]
     public DateTime TimeInfo { get; set; }
     [Description("运行时间")]
     public string RunTime { get; set; }
    

     public RunTimeInfo Clone()
     {
         return new RunTimeInfo()
         {
             TimeInfo = this.TimeInfo,
             RunTime = this.RunTime
         };
     }


 }
csharp 复制代码
 public class DynamicModelCacheKeyFactoryRun : IModelCacheKeyFactory
 {
     public object Create(DbContext context)
         => context is EfContextRunInfo dynamicContext
             ? (context.GetType(), dynamicContext.CreateDateTime)
             : (object)context.GetType();
 }
csharp 复制代码
 public class EfContextRunInfo : DbContext
 {
     public DateTime CreateDateTime { get; set; }

     public static string connectionString
     {
         get
         {
             return $"Data Source={Environment.CurrentDirectory}\\RunTime\\{DateTime.Now.ToString("yyyy-MM-dd")}.db";
         }
     }

     public bool IsSave = true;

     public string DynamicConnectionString;

     public DbSet<RunTimeInfo> MdDatas { get; set; }

     public EfContextRunInfo()
     {

     }

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         if (!optionsBuilder.IsConfigured)
         {
             optionsBuilder.UseSqlite(IsSave ? connectionString : DynamicConnectionString).ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactoryRun>();
         }
     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Entity<RunTimeInfo>(entity =>
         {
             entity.ToTable(CreateDateTime.ToString("yyyyMMdd"));

             entity.Property(e => e.Id)
                  .IsRequired()
                  .HasColumnName("Id")
                  .HasColumnType("INTEGER")
                  .ValueGeneratedOnAdd();


             entity.Property(e => e.TimeInfo)
                 .IsRequired()
                 .HasColumnName("TimeInfo")
                 .HasColumnType("DATETIME")
                 ;

             entity.Property(e => e.RunTime)
                   .IsRequired()
                   .HasColumnName("RunTime")
                   .HasColumnType("TEXT")
                   ;
             entity.HasKey("Id");
         });

     }

 }

添加数据,查找数据

csharp 复制代码
  static ConcurrentQueue<RunTimeInfo> runTimeInfo = new ConcurrentQueue<RunTimeInfo>();
    public Form1()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        AddRunTimeData();
    }

    public static bool AddRunTimeData()
    {
        using (EfContextRunInfo context = new EfContextRunInfo { CreateDateTime = DateTime.Now })
        {
            try
            {
                if (!Directory.Exists($"{Environment.CurrentDirectory}\\RunTime\\"))
                {
                    // 文件夹不存在则创建
                    Directory.CreateDirectory($"{Environment.CurrentDirectory}\\RunTime\\");
                }

                context.Database.EnsureCreated();
                //RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService<IDatabaseCreator>();
                //databaseCreator.CreateTables();
            }
            catch (Microsoft.Data.Sqlite.SqliteException ex)
            {
                //Logger.Debug(ex.Message);
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
                return false;
            }

            while (runTimeInfo.TryDequeue(out var mdData))
            {
                context.MdDatas.Add(mdData);
            }

            context.SaveChangesAsync();
        }

        return true;
    }

    private void btnAddData_Click(object sender, EventArgs e)
    {
        runTimeInfo.Enqueue(new RunTimeInfo() { TimeInfo = DateTime.Now, RunTime = "1" });
    }
    List<RunTimeInfo> mdDataList = new List<RunTimeInfo>();
    private void btnQuary_Click_1(object sender, EventArgs e)
    {
        using (EfContextRunInfo context = new EfContextRunInfo { CreateDateTime = DateTime.Now, IsSave = false, DynamicConnectionString = $"Data Source={Environment.CurrentDirectory}\\RunTime\\{DateTime.Now.ToString("yyyy-MM-dd")}.db" })
        {
            try
            {
                context.Database.EnsureCreated();
                var mdDatas = context.MdDatas.Where(md => md.Id>2);


                mdDataList = mdDataList.Union(mdDatas.ToList()).ToList();
            }
            catch (Microsoft.Data.Sqlite.SqliteException ex)
            {
                //Debug.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
               
            }
        }
    }
}
相关推荐
2301_80220193关注我9 分钟前
Parameters参数、增删改标签、事务、typeAliases
java·数据库·windows
夜间出没的AGUI43 分钟前
zjy-sqlite-manage使用文档v1
数据库·oracle
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 小时前
mysql 和 java 对应数据类型
java·数据库·mysql
TechCraftsman数据库专栏1 小时前
为什么需要 ElasticSearch
数据库·elasticsearch
sin22011 小时前
mysql事务
数据库·mysql·oracle
scc21402 小时前
mysql中redolog、binlog
数据库·mysql·oracle
2401_854391082 小时前
Spring Boot框架下租房管理系统的设计与实现
数据库·spring boot·php
2401_857617622 小时前
Spring Boot框架在中小企业设备管理中的创新应用
数据库·spring boot·后端
会飞的土拨鼠呀2 小时前
Centos7.9安装MySQL(二进制)
android·数据库·mysql
白总Server2 小时前
Gateway解说
服务器·网络·数据库·web安全·架构·php·idc