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);
               
            }
        }
    }
}
相关推荐
云和数据.ChenGuang8 分钟前
Django 应用安装脚本 – 如何将应用添加到 INSTALLED_APPS 设置中 原创
数据库·django·sqlite
woshilys36 分钟前
sql server 查询对象的修改时间
运维·数据库·sqlserver
Hacker_LaoYi36 分钟前
SQL注入的那些面试题总结
数据库·sql
建投数据2 小时前
建投数据与腾讯云数据库TDSQL完成产品兼容性互认证
数据库·腾讯云
Hacker_LaoYi3 小时前
【渗透技术总结】SQL手工注入总结
数据库·sql
岁月变迁呀3 小时前
Redis梳理
数据库·redis·缓存
独行soc3 小时前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍06-基于子查询的SQL注入(Subquery-Based SQL Injection)
数据库·sql·安全·web安全·漏洞挖掘·hw
你的微笑,乱了夏天3 小时前
linux centos 7 安装 mongodb7
数据库·mongodb
工业甲酰苯胺3 小时前
分布式系统架构:服务容错
数据库·架构
独行soc4 小时前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍08-基于时间延迟的SQL注入(Time-Based SQL Injection)
数据库·sql·安全·渗透测试·漏洞挖掘