Skip to content

Commit

Permalink
## v0.3.19
Browse files Browse the repository at this point in the history
- 兼容 GetTableByEntity 有可能因为传入数组类型的错误;
- 修复 UnitOfWork 事务创建逻辑 bug;
- 增加 FreeSql.DbContext 扩展包;
- 调整 UnitOfWork、DbContext 不提交时默认会回滚;
  • Loading branch information
28810 authored and 28810 committed Mar 20, 2019
1 parent 1dccf99 commit 3fd971b
Show file tree
Hide file tree
Showing 21 changed files with 488 additions and 15 deletions.
70 changes: 70 additions & 0 deletions Examples/dbcontext_01/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace dbcontext_01.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{

IFreeSql _orm;
public ValuesController(SongContext songContext, IFreeSql orm) {

_orm = orm;

}

// GET api/values
[HttpGet]
async public Task<string> Get()
{

long id = 0;

try {
using (var ctx = new SongContext()) {

id = await ctx.Songs.Insert(new Song { }).ExecuteIdentityAsync();

var item = await ctx.Songs.Select.Where(a => a.Id == id).FirstAsync();

throw new Exception("回滚");

}
} catch {
var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();

throw;
}
}

// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
49 changes: 49 additions & 0 deletions Examples/dbcontext_01/DbContexts/SongContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using FreeSql;
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;

namespace dbcontext_01 {

public class SongContext : DbContext {

public DbSet<Song> Songs { get; set; }
public DbSet<Song> Tags { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder builder) {
builder.UseFreeSql(dbcontext_01.Startup.Fsql);
}
}


public class Song {
[Column(IsIdentity = true)]
public int Id { get; set; }
public DateTime? Create_time { get; set; }
public bool? Is_deleted { get; set; }
public string Title { get; set; }
public string Url { get; set; }

public virtual ICollection<Tag> Tags { get; set; }
}
public class Song_tag {
public int Song_id { get; set; }
public virtual Song Song { get; set; }

public int Tag_id { get; set; }
public virtual Tag Tag { get; set; }
}

public class Tag {
[Column(IsIdentity = true)]
public int Id { get; set; }
public int? Parent_id { get; set; }
public virtual Tag Parent { get; set; }

public decimal? Ddd { get; set; }
public string Name { get; set; }

public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
24 changes: 24 additions & 0 deletions Examples/dbcontext_01/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace dbcontext_01
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
68 changes: 68 additions & 0 deletions Examples/dbcontext_01/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using FreeSql;
using FreeSql.DataAnnotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace dbcontext_01
{
public class Startup
{
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;

Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10")
.UseLogger(loggerFactory.CreateLogger<IFreeSql>())
.UseAutoSyncStructure(true)
.UseLazyLoading(true)

.UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
.Build();
}

public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new Info {
Version = "v1",
Title = "FreeSql.DbContext API"
});
//options.IncludeXmlComments(xmlPath);
});

services.AddSingleton<IFreeSql>(Fsql);
services.AddFreeDbContext<SongContext>(options => options.UseFreeSql(Fsql));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");

loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();

app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
}
}
9 changes: 9 additions & 0 deletions Examples/dbcontext_01/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
8 changes: 8 additions & 0 deletions Examples/dbcontext_01/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
19 changes: 19 additions & 0 deletions Examples/dbcontext_01/dbcontext_01.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="4.0.1" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\FreeSql.DbContext\FreeSql.DbContext.csproj" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion Examples/repository_01/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
}

public IConfiguration Configuration { get; }
public IFreeSql Fsql { get; }
public static IFreeSql Fsql { get; private set; }

public IServiceProvider ConfigureServices(IServiceCollection services) {

Expand Down
94 changes: 94 additions & 0 deletions FreeSql.DbContext/DbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using SafeObjectPool;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Data.Common;
using System.Linq;
using System.Reflection;

namespace FreeSql {
public abstract class DbContext : IDisposable {

internal IFreeSql _orm;
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");

Object<DbConnection> _conn;
DbTransaction _tran;

static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
protected DbContext() {

var builder = new DbContextOptionsBuilder();
OnConfiguring(builder);
_orm = builder._fsql;

var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());

foreach (var prop in props) {
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);

prop.SetValue(this, set);
AllSets.Add(prop, set);
}
}

protected virtual void OnConfiguring(DbContextOptionsBuilder builder) {

}

public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
public object Set(Type entityType) => Activator.CreateInstance(typeof(BaseDbSet<>).MakeGenericType(entityType), this);

protected Dictionary<PropertyInfo, object> AllSets => new Dictionary<PropertyInfo, object>();

public void SaveChanges() {
Commit();
}

void ReturnObject() {
_fsql.Ado.MasterPool.Return(_conn);
_tran = null;
_conn = null;
}
internal DbTransaction GetOrBeginTransaction(bool isCreate = true) {

if (_tran != null) return _tran;
if (isCreate == false) return null;
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);

_conn = _fsql.Ado.MasterPool.Get();
try {
_tran = _conn.Value.BeginTransaction();
} catch {
ReturnObject();
throw;
}
return _tran;
}

void Commit() {
if (_tran != null) {
try {
_tran.Commit();
} finally {
ReturnObject();
}
}
}
void Rollback() {
if (_tran != null) {
try {
_tran.Rollback();
} finally {
ReturnObject();
}
}
}
public void Dispose() {
this.Rollback();
}
}
}
17 changes: 17 additions & 0 deletions FreeSql.DbContext/DbContextOptionsBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace FreeSql {
public class DbContextOptionsBuilder {

internal IFreeSql _fsql;
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) {
_fsql = orm;
return this;
}
}
}
Loading

0 comments on commit 3fd971b

Please sign in to comment.