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);
               
            }
        }
    }
}
相关推荐
The_Ticker24 分钟前
CFD平台如何接入实时行情源
java·大数据·数据库·人工智能·算法·区块链·软件工程
Elastic 中国社区官方博客30 分钟前
Elasticsearch 开放推理 API 增加了对 IBM watsonx.ai Slate 嵌入模型的支持
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
企鹅侠客35 分钟前
ETCD调优
数据库·etcd
Json_1817901448041 分钟前
电商拍立淘按图搜索API接口系列,文档说明参考
前端·数据库
煎饼小狗1 小时前
Redis五大基本类型——Zset有序集合命令详解(命令用法详解+思维导图详解)
数据库·redis·缓存
永乐春秋1 小时前
WEB-通用漏洞&SQL注入&CTF&二次&堆叠&DNS带外
数据库·sql
打鱼又晒网2 小时前
【MySQL】数据库精细化讲解:内置函数知识穿透与深度学习解析
数据库·mysql
大白要努力!2 小时前
android 使用SQLiteOpenHelper 如何优化数据库的性能
android·数据库·oracle
tatasix3 小时前
MySQL UPDATE语句执行链路解析
数据库·mysql
南城花随雪。3 小时前
硬盘(HDD)与固态硬盘(SSD)详细解读
数据库