{"id":16640063,"url":"https://github.com/2881099/freesql.dbcontext","last_synced_at":"2025-09-11T23:18:04.650Z","repository":{"id":78645870,"uuid":"178763974","full_name":"2881099/FreeSql.DbContext","owner":"2881099","description":"FreeSql 扩展包，实现真正的 ORM，Repository DbContext UnitOfWork 实现。","archived":false,"fork":false,"pushed_at":"2019-06-26T02:20:07.000Z","size":158,"stargazers_count":40,"open_issues_count":2,"forks_count":13,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-08-01T01:07:10.941Z","etag":null,"topics":["codefirst","dbcontext","entity","orm"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/2881099.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-04-01T01:31:16.000Z","updated_at":"2025-07-04T10:07:35.000Z","dependencies_parsed_at":null,"dependency_job_id":"e34843d2-a021-42dc-87c6-2f1a02aafa44","html_url":"https://github.com/2881099/FreeSql.DbContext","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/2881099/FreeSql.DbContext","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2881099%2FFreeSql.DbContext","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2881099%2FFreeSql.DbContext/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2881099%2FFreeSql.DbContext/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2881099%2FFreeSql.DbContext/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/2881099","download_url":"https://codeload.github.com/2881099/FreeSql.DbContext/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2881099%2FFreeSql.DbContext/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270856775,"owners_count":24657700,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-17T02:00:09.016Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codefirst","dbcontext","entity","orm"],"created_at":"2024-10-12T07:07:46.346Z","updated_at":"2025-08-17T14:05:52.560Z","avatar_url":"https://github.com/2881099.png","language":"C#","readme":"\n# 源码于【2019年06月26日】移至 FreeSql 仓储维护。。。\n\n这是 [FreeSql](https://github.com/2881099/FreeSql) 衍生出来的扩展包，包含 DbContext \u0026 DbSet、Repository \u0026 UnitOfWork 实现面向对象的特性（QQ群：4336577）。\n\n\u003e dotnet add package FreeSql.DbContext\n\n## 更新日志\n\n### v0.6.5\n\n- 修复 Repository 联级保存的 bug；\n- 添加工作单元开启方法；\n- 适配 .net framework 4.5、netstandard 2.0；\n\n### v0.6.1\n\n- 拆分 FreeSql 小包引用，各数据库单独包、延时加载包；\n- FreeSql.Extensions.LazyLoading\n- FreeSql.Provider.MySql\n- FreeSql.Provider.PostgreSQL\n- FreeSql.Provider.SqlServer\n- FreeSql.Provider.Sqlite\n- FreeSql.Provider.Oracle\n- 移除 IFreeSql.Cache，以及 ISelect.Caching 方法；\n- 移除 IFreeSql.Log，包括内部原有的日志输出，改为 Trace.WriteLine；\n- IAdo.Query\\\u003cdynamic\\\u003e 读取返回变为 List\\\u003cDictionary\\\u003cstring, object\\\u003e\\\u003e；\n- 定义 IFreeSql 和以前一样，移除了 UseCache、UseLogger 方法；\n\n## DbContext \u0026 DbSet\n\n```csharp\nusing (var ctx = new SongContext()) {\n    var song = new Song { BigNumber = \"1000000000000000000\" };\n    ctx.Songs.Add(song);\n\n    song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();\n    ctx.Songs.Update(song);\n\n    var tag = new Tag {\n        Name = \"testaddsublist\",\n        Tags = new[] {\n            new Tag { Name = \"sub1\" },\n            new Tag { Name = \"sub2\" },\n            new Tag {\n                Name = \"sub3\",\n                Tags = new[] {\n                    new Tag { Name = \"sub3_01\" }\n                }\n            }\n        }\n    };\n    ctx.Tags.Add(tag);\n\n    ctx.SaveChanges();\n}\n```\n\n## Repository \u0026 UnitOfWork\n\n仓储与工作单元一起使用，工作单元具有事务特点。\n\n```csharp\nusing (var unitOfWork = fsql.CreateUnitOfWork()) {\n    var songRepository = unitOfWork.GetRepository\u003cSong, int\u003e();\n    var tagRepository = unitOfWork.GetRepository\u003cTag, int\u003e();\n\n    var song = new Song { BigNumber = \"1000000000000000000\" };\n    songRepository.Insert(song);\n\n    songRepository.Update(song);\n\n    song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString();\n    songRepository.Update(song);\n\n    var tag = new Tag {\n        Name = \"testaddsublist\",\n        Tags = new[] {\n            new Tag { Name = \"sub1\" },\n            new Tag { Name = \"sub2\" },\n            new Tag {\n                Name = \"sub3\",\n                Tags = new[] {\n                    new Tag { Name = \"sub3_01\" }\n                }\n            }\n        }\n    };\n    tagRepository.Insert(tag);\n\n    ctx.Commit();\n}\n```\n\n## Repository\n\n简单使用仓储，有状态跟踪，它不包含事务的特点。\n\n```csharp\nvar songRepository = fsql.GetRepository\u003cSong, int\u003e();\nvar song = new Song { BigNumber = \"1000000000000000000\" };\nsongRepository.Insert(song);\n```\n\n## IFreeSql 核心定义\n\n```csharp\nvar fsql = new FreeSql.FreeSqlBuilder()\n    .UseConnectionString(FreeSql.DataType.Sqlite, @\"Data Source=|DataDirectory|\\dd2.db;Pooling=true;Max Pool Size=10\")\n    .UseAutoSyncStructure(true)\n    .UseNoneCommandParameter(true)\n\n    .UseMonitorCommand(cmd =\u003e Trace.WriteLine(cmd.CommandText))\n    .Build();\n\npublic class Song {\n    [Column(IsIdentity = true)]\n    public int Id { get; set; }\n    public string BigNumber { get; set; }\n\n    [Column(IsVersion = true)] //乐观锁\n    public long versionRow { get; set; }\n}\npublic class Tag {\n    [Column(IsIdentity = true)]\n    public int Id { get; set; }\n\n    public int? Parent_id { get; set; }\n    public virtual Tag Parent { get; set; }\n\n    public string Name { get; set; }\n\n    public virtual ICollection\u003cTag\u003e Tags { get; set; }\n}\n\npublic class SongContext : DbContext {\n    public DbSet\u003cSong\u003e Songs { get; set; }\n    public DbSet\u003cTag\u003e Tags { get; set; }\n\n    protected override void OnConfiguring(DbContextOptionsBuilder builder) {\n        builder.UseFreeSql(fsql);\n    }\n}\n```\n\n# 过滤器与验证\n\n假设我们有User(用户)、Topic(主题)两个实体，在领域类中定义了两个仓储：\n\n```csharp\nvar userRepository = fsql.GetGuidRepository\u003cUser\u003e();\nvar topicRepository = fsql.GetGuidRepository\u003cTopic\u003e();\n```\n\n在开发过程中，总是担心 topicRepository 的数据安全问题，即有可能查询或操作到其他用户的主题。因此我们在v0.0.7版本进行了改进，增加了 filter lambad 表达式参数。\n\n```csharp\nvar userRepository = fsql.GetGuidRepository\u003cUser\u003e(a =\u003e a.Id == 1);\nvar topicRepository = fsql.GetGuidRepository\u003cTopic\u003e(a =\u003e a.UserId == 1);\n```\n\n* 在查询/修改/删除时附加此条件，从而达到不会修改其他用户的数据；\n* 在添加时，使用表达式验证数据的合法性，若不合法则抛出异常；\n\n# 分表与分库\n\nFreeSql 提供 AsTable 分表的基础方法，GuidRepository 作为分存式仓储将实现了分表与分库（不支持跨服务器分库）的封装。\n\n```csharp\nvar logRepository = fsql.GetGuidRepository\u003cLog\u003e(null, oldname =\u003e $\"{oldname}_{DateTime.Now.ToString(\"YYYYMM\")}\");\n```\n\n上面我们得到一个日志仓储按年月分表，使用它 CURD 最终会操作 Log_201903 表。\n\n合并两个仓储，实现分表下的联表查询：\n\n```csharp\nfsql.GetGuidRepository\u003cUser\u003e().Select.FromRepository(logRepository)\n    .LeftJoin\u003cLog\u003e(b =\u003e b.UserId == a.Id)\n    .ToList();\n```\n\n注意事项：\n\n* 不能使用 CodeFirst 迁移分表，开发环境时仍然可以迁移 Log 表；\n* 不可在分表分库的实体类型中使用《延时加载》；\n\n# 历史版本\n\n### v0.5.23\n\n- 增加 DbSet/Repository FlushState 手工清除状态管理数据；\n\n### v0.5.21\n\n- 修复 AddOrUpdate/InsertOrUpdate 当主键无值时，仍然查询了一次数据库；\n- 增加 查询数据时 TrackToList 对导航集合的状态跟踪；\n- 完善 AddOrUpdateNavigateList 联级保存，忽略标记 IsIgnore 的集合属性；\n- 完成 IFreeSql.Include、IncludeMany 功能；\n\n### v0.5.12\n\n- 增加 工作单元开关，可在任意 Insert/Update/Delete 之前调用，以关闭工作单元使其失效；[PR #1](https://github.com/2881099/FreeSql.DbContext/pull/1)\n\n### v0.5.9\n\n- 增加 linq to sql 的查询语法，以及单元测试，[wiki](https://github.com/2881099/FreeSql/wiki/LinqToSql)；\n- 修复 EnableAddOrUpdateNavigateList 设置对异步方法无效的 bug；\n\n### v0.5.8\n\n- 增加 IFreeSql.SetDbContextOptions 设置 DbContext 的功能：开启或禁用连级一对多导航集合属性保存的功能，EnableAddOrUpdateNavigateList（默认开启）；\n- 增加 IUnitOfWork.IsolationLevel 设置事务级别；\n\n### v0.5.7\n\n- 修复 UnitOfWork.GetRepository() 事务 bug，原因：仓储的每步操作都提交了事务；\n\n### v0.5.5\n\n- 修复 MapEntityValue 对 IsIgnore 未处理的 bug；\n\n### v0.5.4\n\n- 修复 Repository 追加导航集合的保存 bug；\n- 公开 IRepository.Orm 对象；\n\n### v0.5.3\n\n- 修复 实体跟踪的 bug，当查询到的实体自增值为 0 时重现；\n- 优化 状态管理字典为 ConcurrentDictionary；\n\n### v0.5.2\n\n- 优化 SqlServer UnitOfWork 使用bug，在 FreeSql 内部解决的；\n- 补充 测试与支持联合主键的自增；\n\n### v0.5.1\n\n- 补充 开放 DbContext.UnitOfWork 对象，方便扩展并保持在同一个事务执行；\n- 补充 增加 DbSet\\\u003cobject\\\u003e、Repository\\\u003cobject\\\u003e 使用方法，配合 AsType(实体类型)，实现弱类型操作；\n- 修复 DbContext.AddOrUpdate 传入 null 时，任然会查询一次数据库的 bug；\n- 优化 DbContext.AddOrUpdate 未添加实体主键的错误提醒；\n- 修复 DbContext.Set\\\u003cobject\\\u003e 缓存的 bug，使用多种弱类型时发生；\n- 修复 IsIgnore 过滤字段后，查询的错误；\n- 修复 全局过滤器功能迁移的遗留 bug；\n\n### v0.4.14\n\n- 优化 Add 时未设置主键的错误提醒；\n\n### v0.4.13\n\n- 补充 Repository 增加 Attach 方法；\n- 优化 Update/AddOrUpdate 实体的时候，若状态管理不存在，尝试查询一次数据库，以便跟踪对象；\n\n### v0.4.12\n\n- 修复 非自增情况下，Add 后再 Update 该实体时，错误（需要先 Attach 或查询）的 bug；\n\n### v0.4.10\n\n- 补充 开放 DbContext.Orm 对象；\n- 修复 OnConfiguring 未配置时注入获取失败的 bug；\n\n### v0.4.6\n\n- 修复 DbSet AddRange/UpdateRange/RemoveRange 参数为空列表时报错，现在不用判断 data.Any() == true 再执行；\n- 增加 DbContext 对 DbSet 的快速代理方法(Add/Update/Remove/Attach)；\n- 增加 DbContext 通用类，命名为：FreeContext，也可以通过 IFreeSql 扩展方法 CreateDbContext 创建；\n- 增加 ISelect NoTracking 扩展方法，查询数据时不追踪（从而提升查询性能）；\n\n### v0.4.5\n\n- 增加 DbSet Attach 方法附加实体，可用于不查询就更新或删除；\n\n### v0.4.2\n\n- 增加 DbSet UpdateAsync/UpdateRangeAsync 方法，当一个实体被更新两次时，会先执行前面的队列；\n- 增加 GetRepository 获取联合主键的适用仓储类；\n- 增加 DbSet 在 Add/Update 时对导航属性(OneToMany) 的处理（AddOrUpdate）；\n\n### v0.4.1\n- 独立 FreeSql.DbContext 项目；\n- 实现 Repository + DbSet 统一的状态跟踪与工作单元；\n- 增加 DbSet AddOrUpdate 方法；\n- 增加 Repository InsertOrUpdate 方法；","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F2881099%2Ffreesql.dbcontext","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F2881099%2Ffreesql.dbcontext","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F2881099%2Ffreesql.dbcontext/lists"}