FrameWork使用EfCore数据库映射举例

时间:2024-10-15 10:06:10

Microsoft.EntityFrameworkCore新的版本不支持FrameWork框架。
这里举例使用旧版本实现数据存取
首先下载
Microsoft.EntityFrameworkCore 版本控制在2.1.14以下
同样下载Microsoft.EntityFrameworkCore.sqlite

举例时间记录

 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
         };
     }


 }
 public class DynamicModelCacheKeyFactoryRun : IModelCacheKeyFactory
 {
     public object Create(DbContext context)
         => context is EfContextRunInfo dynamicContext
             ? (context.GetType(), dynamicContext.CreateDateTime)
             : (object)context.GetType();
 }
 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");
         });

     }

 }

添加数据,查找数据

  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);
               
            }
        }
    }
}