脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

FreeSql CodeFirst设计模式

3785人阅读 2022/1/4 16:11 总访问:645248 评论:0 收藏:0 手机
分类: Free sql

前言

freesql Code First 设计模式

freesql 支持更多的数据库特性
而不只是支持基础的数据类型,这既是优点也是缺点,优点是充分利用数据库特性辅助开发,缺点是切换数据库变得困难。

如果实体类属性,与数据库表字段不完整映射的时候,未映射的字段有可能发生丢失。

FreeSql提供两种CodeFirst移迁方法,自动和手动。

自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后迁移执行创建或修改

                IFreeSql fsql = new FreeSqlBuilder()
                //指定数据库类型以及数据库连接
                .UseConnectionString(DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=oa;Pooling=true;Min Pool Size=1;uid=sa;pwd=Aa123456;Max Pool Size=5;Encrypt=True;TrustServerCertificate=True;database=oa")
                //aop监听sql
                .UseMonitorCommand(cmd =>//执行前
                {
                }, (cmd, valueString) =>//执行后
                {

                })
                .UseAutoSyncStructure(true)//CodeFirst自动同步将实体同步到数据库结构(开发阶段必备),默认是true,正式环境请改为false
                .Build();

禁用迁移

当【实体类】对应的是数据库【视图】或者其他时,可通过 [Table(DisableSyncStructure = true)] 禁用指定的实体迁移操作。




freesql 不能为SQL server ,mysql创建数据库,需要自行创建数据库  

Code First创建表结构

一、单张表创建

创建数据表实体类
属性添加表名,主键,自增


           //同步实体类型到数据库(单个)
            _FreeSql.CodeFirst.SyncStructure<Student>();

二、创建多个表结构

定义一个表模型类,将每张表设置一个name

 public class Model
    {

        [Table(Name = "oa.dbo.Teacher")]
        public class Teacher 
        {
            [Column(IsPrimary = true, IsIdentity = true)]
            //
            public string TId { get; set; }
            //
            public string Tname { get; set; }
            //
            public string Tsex { get; set; }
            //
            public DateTime Tage { get; set; }

        }

        [Table(Name = "oa.dbo.Class")]
        public class Class
        {
            [Column(IsPrimary = true, IsIdentity = true)]
            //唯一ID
            public string CId { get; set; }
            //名称
            public string Cname { get; set; }
            //年级
            public string CClass { get; set; }
        }
   }

创建完成后通过反射拿到model类下的所有表模型

        /// <summary>
        /// 获取Model类下的所有数据库模型类,并拿到type集合
        /// </summary>
        /// <returns></returns>
        public static Type[] GetTypesByTableAttribute()
        {
            List<Type> tableAssembies = new List<Type>();
            foreach (Type type in Assembly.GetAssembly(typeof(Model)).GetExportedTypes())
                foreach (Attribute attribute in type.GetCustomAttributes())
                    if (attribute is TableAttribute tableAttribute)
                        if (tableAttribute.DisableSyncStructure == false)
                            tableAssembies.Add(type);

            return tableAssembies.ToArray();
        }

最后执行

           //同步实体类型到数据库(多个)
            _FreeSql.CodeFirst.SyncStructure(GetTypesByTableAttribute());

三、命名空间创建

Entity文件夹下的实体类命名空间都是以WebApplication2.EntityList 命名



通过反射拿到同一命名空间下所有的实体类

public static Type[] GetTypesByNameSpace(){
    List<Type> tableAssembies = new List<Type>();
    List<string> entitiesFullName = new List<string>()
    {
        "WebApplication2.EntityList",
    };
    foreach (Type type in Assembly.GetAssembly(typeof(Test1)).GetExportedTypes())
        foreach (var fullname in entitiesFullName)
            if (type.FullName.StartsWith(fullname) && type.IsClass)
                tableAssembies.Add(type);

    return tableAssembies.ToArray();}

最后执行

           //同步实体类型到数据库(多个)
            _FreeSql.CodeFirst.SyncStructure(GetTypesByNameSpace());


更多请查看freesql官方文档
指南 | FreeSql 官方文档

评价