Skip to content

Commit

Permalink
Support cancel create
Browse files Browse the repository at this point in the history
  • Loading branch information
Kation committed Jan 15, 2024
1 parent 228eec7 commit 944333d
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,21 @@ public virtual async Task<IViewModel<TListDTO>> List([FromService] IEntityContex
queryable = entityQueryEventArgs.Queryable;
bool isOrdered = entityQueryEventArgs.IsOrdered;
OnListQuery(ref queryable, ref isOrdered);
var dtoQueryable = queryable.ProjectTo<TListDTO>(mapper.ConfigurationProvider);
OnListQuery(ref dtoQueryable, ref isOrdered);
if (!isOrdered)
{
var sortProperty = EntityDescriptor.GetMetadata<TListDTO>().SortProperty;
var sortProperty = EntityDescriptor.GetMetadata<TEntity>().SortProperty;
if (sortProperty != null)
{
var parameter = Expression.Parameter(typeof(TListDTO));
dynamic express = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TListDTO), sortProperty.ClrType), Expression.Property(parameter, sortProperty.ClrName), parameter);
if (EntityDescriptor.GetMetadata<TListDTO>().IsSortDescending)
dtoQueryable = Queryable.OrderByDescending(dtoQueryable, express);
var parameter = Expression.Parameter(typeof(TEntity));
dynamic express = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TEntity), sortProperty.ClrType), Expression.Property(parameter, sortProperty.ClrName), parameter);
if (EntityDescriptor.GetMetadata<TEntity>().IsSortDescending)
queryable = Queryable.OrderByDescending(queryable, express);
else
dtoQueryable = Queryable.OrderBy(dtoQueryable, express);
queryable = Queryable.OrderBy(queryable, express);
}
}
var dtoQueryable = queryable.ProjectTo<TListDTO>(mapper.ConfigurationProvider);
//OnListQuery(ref dtoQueryable, ref isOrdered);
ViewModel<TListDTO> model = new ViewModel<TListDTO>(dtoQueryable);
await RaiseEvent(new EntityQueryModelCreatedEventArgs<TListDTO>(model));
return model;
Expand All @@ -66,10 +66,10 @@ protected virtual void OnListQuery(ref IQueryable<TEntity> queryable, ref bool i

}

protected virtual void OnListQuery(ref IQueryable<TListDTO> queryable, ref bool isOrdered)
{
//protected virtual void OnListQuery(ref IQueryable<TListDTO> queryable, ref bool isOrdered)
//{

}
//}

#endregion

Expand All @@ -92,10 +92,19 @@ public virtual async Task<IUpdateModel<TListDTO>> Create([FromService] IEntityCo
mapper.Map(dto, entity);
await RaiseEvent(new EntityMappedEventArgs<TEntity, TCreateDTO>(entity, dto));
entityContext.Add(entity);
await RaiseEvent(new EntityPreCreateEventArgs<TEntity>(entity));
await entityContext.Database.SaveAsync();
await RaiseEvent(new EntityCreatedEventArgs<TEntity>(entity));
model.IsSuccess = true;
var preCreateEventArgs = new EntityPreCreateEventArgs<TEntity>(entity);
await RaiseEvent(preCreateEventArgs);
if (preCreateEventArgs.IsCanceled)
{
model.IsSuccess = true;
entityContext.Detach(entity);
}
else
{
await entityContext.Database.SaveAsync();
await RaiseEvent(new EntityCreatedEventArgs<TEntity>(entity));
model.IsSuccess = true;
}
model.Item = mapper.Map<TListDTO>(entity);
return model;
}
Expand All @@ -114,13 +123,22 @@ public virtual async Task<IUpdateRangeModel<TListDTO>> CreateRange([FromService]
mapper.Map(dto, entity);
await RaiseEvent(new EntityMappedEventArgs<TEntity, TCreateDTO>(entity, dto));
entityContext.Add(entity);
await RaiseEvent(new EntityPreCreateEventArgs<TEntity>(entity));
var listDto = mapper.Map<TListDTO>(entity);
entities.Add(listDto, entity);
model.AddItem(listDto);
var preCreateEventArgs = new EntityPreCreateEventArgs<TEntity>(entity);
await RaiseEvent(preCreateEventArgs);
if (preCreateEventArgs.IsCanceled)
{
entityContext.Detach(entity);
}
else
{
var listDto = mapper.Map<TListDTO>(entity);
entities.Add(listDto, entity);
model.AddItem(listDto);
}
}
else
{
model.IsSuccess = false;
model.AddItem(null, results.Where(t => t.ErrorMessage != null).Select(t => new KeyValuePair<string, string>(t.MemberNames.FirstOrDefault() ?? string.Empty, t.ErrorMessage!)).ToList());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,7 @@ public EntityPreCreateEventArgs(T entity)
}

public T Entity { get; }

public bool IsCanceled { get; set; }
}
}
87 changes: 83 additions & 4 deletions test/Wodsoft.ComBoost.Data.Test/EntityDomainServiceTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
Expand All @@ -18,13 +19,22 @@ namespace Wodsoft.ComBoost.Data.Test
{
public class EntityDomainServiceTest
{
private SqliteConnection _connection;

private void CreateConnection()
{
_connection = new SqliteConnection("Filename=:memory:");
_connection.Open();
}

[Fact]
public async Task CURDTest()
{
CreateConnection();
var mock = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddDbContext<DataContext>();
services.AddDbContext<DataContext>(options => options.UseSqlite(_connection));
services.AddEFCoreContext<DataContext>();
services.AddComBoost()
.AddLocalService(builder =>
Expand Down Expand Up @@ -80,7 +90,7 @@ await mock.RunAsync(async sp =>
Assert.Equal(model.Item.CreationDate, model.Item.ModificationDate);
user = model.Item;
});

await mock.RunAsync(async sp =>
{
var template = sp.GetRequiredService<IEntityDomainTemplate<UserDto>>();
Expand Down Expand Up @@ -116,10 +126,11 @@ await mock.RunAsync(async sp =>
[Fact]
public async Task ValidationTest()
{
CreateConnection();
var mock = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddDbContext<DataContext>(options => options.UseSqlite("Filename=:memory:"));
services.AddDbContext<DataContext>(options => options.UseSqlite(_connection));
services.AddEFCoreContext<DataContext>();
services.AddComBoost()
.AddLocalService(builder =>
Expand Down Expand Up @@ -156,5 +167,73 @@ await mock.RunAsync(async sp =>
Assert.Contains(model.ErrorMessage, t => t.Key == nameof(UserDto.Email));
});
}

[Fact]
public async Task CancelCreateTest()
{
CreateConnection();
var mock = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddDbContext<DataContext>(options => options.UseSqlite(_connection));
services.AddEFCoreContext<DataContext>();
services.AddComBoost()
.AddLocalService(builder =>
{
builder.AddEntityService<UserEntity, UserDto>();
})
.AddMock();
services.AddAutoMapper(config =>
{
config.CreateMap<UserEntity, UserDto>()
.ForMember(t => t.Password, options => options.Ignore());
config.CreateMap<UserDto, UserEntity>()
.ForMember(t => t.Password, options => options.Ignore())
.AfterMap((dto, entity) =>
{
if (!string.IsNullOrEmpty(dto.Password))
entity.SetPassword(dto.Password);
});
});
})
.Build();

mock.Run(sp =>
{
sp.GetRequiredService<DataContext>().Database.EnsureCreated();
});

await mock.RunAsync(async sp =>
{
var template = sp.GetRequiredService<IEntityDomainTemplate<UserDto>>();
var viewModel = await template.List();
Assert.Empty(viewModel.Items);
});

await mock.RunAsync(async sp =>
{
var template = sp.GetRequiredService<IEntityDomainTemplate<UserDto>>();
template.Context.EventManager.AddEventHandler<EntityPreCreateEventArgs<UserEntity>>((context, e) =>
{
e.IsCanceled = true;
return Task.CompletedTask;
});
var model = await template.Create(new UserDto
{
UserName = "test1",
Email = "test1@test.com",
DisplayName = "Test Account 1",
Password = "123456"
});
Assert.True(model.IsSuccess);
});

await mock.RunAsync(async sp =>
{
var template = sp.GetRequiredService<IEntityDomainTemplate<UserDto>>();
var viewModel = await template.List();
Assert.Empty(viewModel.Items);
});
}
}
}
1 change: 1 addition & 0 deletions test/Wodsoft.ComBoost.Test.Common/Entities/UserEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Wodsoft.ComBoost.Test.Entities
{
public class UserEntity: UserBase
{
[Key]
[Required]
[MaxLength(16)]
public string UserName { get; set; }
Expand Down

0 comments on commit 944333d

Please sign in to comment.