apply fix on Query methods in Base EF Repository for Fixing total Pages and total Filtered Pages ...

This commit is contained in:
2025-12-26 01:18:16 +03:30
parent 27325a7904
commit eaf948f8c1
+283 -189
View File
@@ -11,10 +11,12 @@ using xDataService.Db;
using xDataService.Extensions; using xDataService.Extensions;
using xDataService.Interfaces; using xDataService.Interfaces;
using xDataService.Models; using xDataService.Models;
using xExceptions.Constants;
using xModels.Base; using xModels.Base;
using xModels.Dtos; using xModels.Dtos;
namespace xDataService.EFRepositories { namespace xDataService.EFRepositories
{
/// <summary> /// <summary>
/// Base EFCore Base Entity Repository Pattern implementation ... /// Base EFCore Base Entity Repository Pattern implementation ...
/// Only Used on EFCore ... /// Only Used on EFCore ...
@@ -24,7 +26,8 @@ namespace xDataService.EFRepositories {
/// <typeparam name="TDbContext">is the DbContext Type</typeparam> /// <typeparam name="TDbContext">is the DbContext Type</typeparam>
public abstract class XBaseEFRepository<T, TKey, TDbContext> : IXBaseRepository<T, TKey> public abstract class XBaseEFRepository<T, TKey, TDbContext> : IXBaseRepository<T, TKey>
where T : XBaseEntity<TKey> where T : XBaseEntity<TKey>
where TDbContext : XDbContext { where TDbContext : XDbContext
{
// //
public readonly DbSet<T> dbSet; public readonly DbSet<T> dbSet;
private readonly IXKeyGenerator<T, TKey> keyGenerator; private readonly IXKeyGenerator<T, TKey> keyGenerator;
@@ -42,7 +45,8 @@ namespace xDataService.EFRepositories {
XDataServiceConfiguration configuration, XDataServiceConfiguration configuration,
IXKeyGenerator<T, TKey> keyGenerator = null, IXKeyGenerator<T, TKey> keyGenerator = null,
IXBaseRepositoryEvents<T> baseRepositoryEvents = null IXBaseRepositoryEvents<T> baseRepositoryEvents = null
) { )
{
this.keyGenerator = keyGenerator; this.keyGenerator = keyGenerator;
// //
this.unitOfWorks = unitOfWorks; this.unitOfWorks = unitOfWorks;
@@ -57,7 +61,8 @@ namespace xDataService.EFRepositories {
public async Task<T> AddAsync( public async Task<T> AddAsync(
T item, T item,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
// Handle Key ... // Handle Key ...
item = await HandleKeyAsync(item); item = await HandleKeyAsync(item);
@@ -68,7 +73,8 @@ namespace xDataService.EFRepositories {
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -83,7 +89,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.AddEvent(new XBaseEventModel<T>(entry.Entity)); .AddEvent(new XBaseEventModel<T>(entry.Entity));
} }
@@ -98,15 +105,19 @@ namespace xDataService.EFRepositories {
public async Task<T> AddOrUpdateAsync( public async Task<T> AddOrUpdateAsync(
T item, T item,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
var isExists = await IsExistsAsync(GetKey(item)); var isExists = await IsExistsAsync(GetKey(item));
if (!isExists) { if (!isExists)
{
return await AddAsync( return await AddAsync(
item, item,
saveChanges saveChanges
); );
} else { }
else
{
return await UpdateAsync( return await UpdateAsync(
GetKey(item), GetKey(item),
item, item,
@@ -118,7 +129,8 @@ namespace xDataService.EFRepositories {
public async Task AddRangeAsync( public async Task AddRangeAsync(
IEnumerable<T> items, IEnumerable<T> items,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
await dbSet.AddRangeAsync( await dbSet.AddRangeAsync(
await Task await Task
@@ -131,7 +143,8 @@ namespace xDataService.EFRepositories {
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -146,7 +159,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.AddManyEvent(new XBaseEventModel<IEnumerable<T>>(null)); .AddManyEvent(new XBaseEventModel<IEnumerable<T>>(null));
} }
@@ -159,32 +173,38 @@ namespace xDataService.EFRepositories {
TKey id, TKey id,
bool softDelete = true, bool softDelete = true,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
// Retrieve Item ... // Retrieve Item ...
var item = await GetAsync( var item = await GetAsync(
id, id,
ignoreSoftDeleteds: false ignoreSoftDeleteds: false
); );
if (item.IsNull ()) { if (item.IsNull())
{
return null; return null;
} }
// //
// Handle Remove ... // Handle Remove ...
EntityEntry<T> entry = null; EntityEntry<T> entry = null;
if (softDelete && configuration.EnableSoftDelete) { if (softDelete && configuration.EnableSoftDelete)
{
// //
item.Deleted = true; item.Deleted = true;
entry = dbSet.Update(item); entry = dbSet.Update(item);
} else { }
else
{
entry = dbSet.Remove(item); entry = dbSet.Remove(item);
} }
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -199,7 +219,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.RemoveEvent(new XBaseEventModel<T>(entry.Entity)); .RemoveEvent(new XBaseEventModel<T>(entry.Entity));
} }
@@ -215,32 +236,38 @@ namespace xDataService.EFRepositories {
T item, T item,
bool softDelete = true, bool softDelete = true,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
// Check item Exists ... // Check item Exists ...
var isExists = await IsExistsAsync( var isExists = await IsExistsAsync(
GetKey(item), GetKey(item),
ignoreSoftDeleteds: false ignoreSoftDeleteds: false
); );
if (!isExists) { if (!isExists)
{
return null; return null;
} }
// //
// Handle Remove ... // Handle Remove ...
EntityEntry<T> entry = null; EntityEntry<T> entry = null;
if (softDelete && configuration.EnableSoftDelete) { if (softDelete && configuration.EnableSoftDelete)
{
// //
item.Deleted = true; item.Deleted = true;
entry = dbSet.Update(item); entry = dbSet.Update(item);
} else { }
else
{
entry = dbSet.Remove(item); entry = dbSet.Remove(item);
} }
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -255,7 +282,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.RemoveEvent(new XBaseEventModel<T>(entry.Entity)); .RemoveEvent(new XBaseEventModel<T>(entry.Entity));
} }
@@ -271,25 +299,31 @@ namespace xDataService.EFRepositories {
IEnumerable<T> items, IEnumerable<T> items,
bool softDelete = true, bool softDelete = true,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
// Handle Remove ... // Handle Remove ...
if (softDelete && configuration.EnableSoftDelete) { if (softDelete && configuration.EnableSoftDelete)
{
// //
foreach (var item in items) { foreach (var item in items)
{
item.Deleted = true; item.Deleted = true;
} }
// //
dbSet.UpdateRange(items); dbSet.UpdateRange(items);
} else { }
else
{
dbSet.RemoveRange(items); dbSet.RemoveRange(items);
} }
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -304,7 +338,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.RemoveManyEvent(new XBaseEventModel<IEnumerable<T>>(null)); .RemoveManyEvent(new XBaseEventModel<IEnumerable<T>>(null));
} }
@@ -313,7 +348,8 @@ namespace xDataService.EFRepositories {
// //
#region Retrieve ... #region Retrieve ...
public IQueryable<T> AsQueryable () { public IQueryable<T> AsQueryable()
{
return dbSet.AsQueryable(); return dbSet.AsQueryable();
} }
@@ -321,7 +357,8 @@ namespace xDataService.EFRepositories {
TKey id, TKey id,
bool ignoreSoftDeleteds = true, bool ignoreSoftDeleteds = true,
bool containsDetail = false bool containsDetail = false
) { )
{
// //
var result = await FindOneAsync(i => var result = await FindOneAsync(i =>
GetKey(i) GetKey(i)
@@ -339,8 +376,10 @@ namespace xDataService.EFRepositories {
public async Task<IEnumerable<T>> GetAllAsync( public async Task<IEnumerable<T>> GetAllAsync(
bool ignoreSoftDeleteds = true, bool ignoreSoftDeleteds = true,
bool containsDetail = false bool containsDetail = false
) { )
return await Task.Run (() => { {
return await Task.Run(() =>
{
// //
var result = GetDbSet( var result = GetDbSet(
containsDetail: containsDetail containsDetail: containsDetail
@@ -348,7 +387,8 @@ namespace xDataService.EFRepositories {
// //
// Handle Soft Deleted Items ... // Handle Soft Deleted Items ...
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
result = result.Where(x => x.Deleted == false); result = result.Where(x => x.Deleted == false);
} }
@@ -361,7 +401,8 @@ namespace xDataService.EFRepositories {
Expression<Func<T, bool>> whereClause, Expression<Func<T, bool>> whereClause,
bool ignoreSoftDeleteds = true, bool ignoreSoftDeleteds = true,
bool containsDetail = false bool containsDetail = false
) { )
{
// //
// Generate Where Function ... // Generate Where Function ...
var whereFunc = whereClause.Compile(); var whereFunc = whereClause.Compile();
@@ -369,7 +410,8 @@ namespace xDataService.EFRepositories {
// //
// Handle Soft Deleted Items ... // Handle Soft Deleted Items ...
Func<T, bool> ignoreSoftDeletedsWhereFunc = null; Func<T, bool> ignoreSoftDeletedsWhereFunc = null;
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
// //
Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false; Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false;
ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile(); ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile();
@@ -385,13 +427,15 @@ namespace xDataService.EFRepositories {
// //
T result = null; T result = null;
await await
foreach (var entity in enumerator) { foreach (var entity in enumerator)
{
// //
var isApproved = whereFunc(entity) && var isApproved = whereFunc(entity) &&
(ignoreSoftDeletedsWhereFunc.IsNull() ? (ignoreSoftDeletedsWhereFunc.IsNull() ?
true : true :
ignoreSoftDeletedsWhereFunc(entity)); ignoreSoftDeletedsWhereFunc(entity));
if (isApproved) { if (isApproved)
{
// //
result = entity; result = entity;
break; break;
@@ -406,7 +450,8 @@ namespace xDataService.EFRepositories {
Expression<Func<T, bool>> whereClause, Expression<Func<T, bool>> whereClause,
bool ignoreSoftDeleteds = true, bool ignoreSoftDeleteds = true,
bool containsDetail = false bool containsDetail = false
) { )
{
// //
// Generate Where Function ... // Generate Where Function ...
var whereFunc = whereClause.Compile(); var whereFunc = whereClause.Compile();
@@ -414,7 +459,8 @@ namespace xDataService.EFRepositories {
// //
// Handle Soft Deleted Items ... // Handle Soft Deleted Items ...
Func<T, bool> ignoreSoftDeletedsWhereFunc = null; Func<T, bool> ignoreSoftDeletedsWhereFunc = null;
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
// //
Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false; Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false;
ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile(); ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile();
@@ -430,13 +476,15 @@ namespace xDataService.EFRepositories {
// //
var result = new List<T>(); var result = new List<T>();
await await
foreach (var entity in enumerator) { foreach (var entity in enumerator)
{
// //
var isApproved = whereFunc(entity) && var isApproved = whereFunc(entity) &&
(ignoreSoftDeletedsWhereFunc.IsNull() ? (ignoreSoftDeletedsWhereFunc.IsNull() ?
true : true :
ignoreSoftDeletedsWhereFunc(entity)); ignoreSoftDeletedsWhereFunc(entity));
if (isApproved) { if (isApproved)
{
result.Add(entity); result.Add(entity);
} }
} }
@@ -448,29 +496,24 @@ namespace xDataService.EFRepositories {
public async Task<XQueryResult<T>> QueryAsync( public async Task<XQueryResult<T>> QueryAsync(
XQuery query, XQuery query,
bool ignoreSoftDeleteds = true bool ignoreSoftDeleteds = true
) { )
{
// //
if (query.PageSize < configuration // Validate ...
.PagingConfiguration if (query.IsNull())
.MinAvailablePageSize) { {
query.PageSize = configuration XException.InvalidArgs.Throw();
.PagingConfiguration
.DefaultPageSize;
} }
// //
if (query.PageSize > configuration // Normalize ...
.PagingConfiguration query = query.NormalizeQuery(configuration);
.MaxAvailablePageSize) {
query.PageSize = configuration
.PagingConfiguration
.MaxAvailablePageSize;
}
// //
// Handle Soft Deleted Items ... // Handle Soft Deleted Items ...
Func<T, bool> ignoreSoftDeletedsWhereFunc = null; Func<T, bool> ignoreSoftDeletedsWhereFunc = null;
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
// //
Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false; Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false;
ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile(); ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile();
@@ -484,107 +527,111 @@ namespace xDataService.EFRepositories {
.AsAsyncEnumerable(); .AsAsyncEnumerable();
// //
var resultItems = new List<T> (); var totalEntities = new List<T>();
await await
foreach (var entity in enumerator) { foreach (var entity in enumerator)
{
// //
var isApproved = (ignoreSoftDeletedsWhereFunc.IsNull() ? var isApproved = (ignoreSoftDeletedsWhereFunc.IsNull() ?
true : true :
ignoreSoftDeletedsWhereFunc(entity)); ignoreSoftDeletedsWhereFunc(entity));
if (isApproved) { if (isApproved)
resultItems.Add (entity); {
totalEntities.Add(entity);
} }
} }
// //
var result = resultItems.AsEnumerable (); var items = totalEntities.AsEnumerable();
var totalItemsCount = items.Count();
//
// Count Total Items ...
var totalItemsCount = result.Count ();
// //
// Apply Filter ... // Apply Filter ...
if (!query.Filter.IsNullOrEmpty ()) { if (!query.Filter.IsNullOrEmpty())
result = await result {
.ApplyFilterAsync<T, TKey> (query.Filter); //
items = items
.ApplyFilter(query.Filter);
} }
int filteredItemsCount = items.Count();
// //
// Count Total Items ... // Count Pages ...
int totalFilteredItemsCount = result.Count (); var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
// //
// Apply Paging ... // Apply Paging ...
result = result items = items
.ToList()
.ApplyPaging( .ApplyPaging(
query.Page, query.Page,
query.PageSize); query.PageSize
);
//
// Apply Sorting ...
if (!query.SortBy.IsNullOrEmpty ()) {
result = result
.ApplySorting<T, TKey> (
query.SortBy,
query.IsAscending);
} }
// //
// Generate Result Object ... // Prepare Result ...
// Query = query, var result = new XQueryResult<T>
var queryResult = new XQueryResult<T> { {
Items = result.AsEnumerable (),
Page = query.Page, Page = query.Page,
Items = items.ToList(),
PageSize = query.PageSize, PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount, TotalItems = totalItemsCount,
TotalPages = await PagesCountAsync ( TotalFilteredPages = filteredPagesCount,
query.PageSize, TotalFilteredItems = filteredItemsCount
totalFilteredItemsCount
),
TotalFilteredItems = totalFilteredItemsCount
}; };
// //
return queryResult; return result;
} }
public async Task<XQueryResult<T>> ConditionalQueryAsync( public async Task<XQueryResult<T>> ConditionalQueryAsync(
Expression<Func<T, bool>> condition, Expression<Func<T, bool>> condition,
XQuery query, XQuery query,
bool ignoreSoftDeleteds = true bool ignoreSoftDeleteds = true
) { )
{
// //
if (query.PageSize < configuration // Validate ...
.PagingConfiguration if (query.IsNull() || condition.IsNull())
.MinAvailablePageSize) { {
query.PageSize = configuration XException.InvalidArgs.Throw();
.PagingConfiguration
.DefaultPageSize;
} }
// //
if (query.PageSize > configuration // Normalize ...
.PagingConfiguration query = query.NormalizeQuery(configuration);
.MaxAvailablePageSize) {
query.PageSize = configuration
.PagingConfiguration
.MaxAvailablePageSize;
}
//
// Generate Where Function ...
var whereFunc = condition.Compile ();
// //
// Handle Soft Deleted Items ... // Handle Soft Deleted Items ...
Func<T, bool> ignoreSoftDeletedsWhereFunc = null; Func<T, bool> ignoreSoftDeletedsWhereFunc = null;
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
// //
Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false; Expression<Func<T, bool>> ignoreSoftDeletedsWhereClause = x => x.Deleted == false;
ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile(); ignoreSoftDeletedsWhereFunc = ignoreSoftDeletedsWhereClause.Compile();
} }
//
// Compile Condition ...
Func<T, bool> conditionFunc = condition.Compile();
// //
// Get Enumerable ... // Get Enumerable ...
var enumerator = GetDbSet( var enumerator = GetDbSet(
@@ -593,73 +640,79 @@ namespace xDataService.EFRepositories {
.AsAsyncEnumerable(); .AsAsyncEnumerable();
// //
var resultItems = new List<T> (); var totalEntities = new List<T>();
await await
foreach (var entity in enumerator) { foreach (var entity in enumerator)
{
// //
var isApproved = whereFunc (entity) && var isApproved = (ignoreSoftDeletedsWhereFunc.IsNull() ?
(ignoreSoftDeletedsWhereFunc.IsNull () ?
true : true :
ignoreSoftDeletedsWhereFunc (entity)); ignoreSoftDeletedsWhereFunc(entity)) &&
if (isApproved) { conditionFunc(entity);
resultItems.Add (entity); if (isApproved)
{
totalEntities.Add(entity);
} }
} }
// //
var result = resultItems.AsQueryable (); var items = totalEntities.AsEnumerable();
var totalItemsCount = items.Count();
//
// Count Total Items ...
var totalItemsCount = result.Count ();
// //
// Apply Filter ... // Apply Filter ...
if (totalItemsCount > 0 && if (!query.Filter.IsNullOrEmpty())
!query.Filter.IsNullOrEmpty ()) { {
result = result //
.ApplyFilter<T, TKey> (query.Filter); items = items
.ApplyFilter(query.Filter);
} }
int filteredItemsCount = items.Count();
// //
// Count Total Items ... // Count Pages ...
var totalFilteredItemsCount = result.Count (); var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
// //
// Apply Paging ... // Apply Paging ...
if (totalItemsCount > 0 && items = items
totalFilteredItemsCount > 0) { .ToList()
result = result
.ApplyPaging( .ApplyPaging(
query.Page, query.Page,
query.PageSize); query.PageSize
);
//
// Apply Sorting ...
if (!query.SortBy.IsNullOrEmpty ()) {
result = result
.ApplySorting<T, TKey> (
query.SortBy,
query.IsAscending);
}
} }
// //
// Generate Result Object ... // Prepare Result ...
var queryResult = new XQueryResult<T> { var result = new XQueryResult<T>
Items = result.AsEnumerable (), {
Page = query.Page, Page = query.Page,
Items = items.ToList(),
PageSize = query.PageSize, PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount, TotalItems = totalItemsCount,
TotalPages = await PagesCountAsync ( TotalFilteredPages = filteredPagesCount,
query.PageSize, TotalFilteredItems = filteredItemsCount
totalFilteredItemsCount
),
TotalFilteredItems = totalFilteredItemsCount
}; };
// //
return queryResult; return result;
} }
// //
@@ -787,7 +840,8 @@ namespace xDataService.EFRepositories {
TKey id, TKey id,
T item, T item,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
// Get Exists Entity ... // Get Exists Entity ...
var existsEntity = await GetAsync( var existsEntity = await GetAsync(
@@ -805,7 +859,8 @@ namespace xDataService.EFRepositories {
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -820,7 +875,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.UpdateEvent(new XBaseEventModel<T>(entry.Entity)); .UpdateEvent(new XBaseEventModel<T>(entry.Entity));
} }
@@ -835,11 +891,13 @@ namespace xDataService.EFRepositories {
public async Task<bool> UpdateRangeAsync( public async Task<bool> UpdateRangeAsync(
IEnumerable<T> items, IEnumerable<T> items,
bool saveChanges = true bool saveChanges = true
) { )
{
// //
items items
.ToList() .ToList()
.ForEach (i => { .ForEach(i =>
{
var entry = dbSet.Attach(i); var entry = dbSet.Attach(i);
entry.State = EntityState.Modified; entry.State = EntityState.Modified;
}); });
@@ -847,7 +905,8 @@ namespace xDataService.EFRepositories {
// //
// Check action is Succeeded or not ... // Check action is Succeeded or not ...
var isSucceed = false; var isSucceed = false;
if (saveChanges) { if (saveChanges)
{
// //
// Get Modified Count ... // Get Modified Count ...
var qResult = await SaveChangesAsync(); var qResult = await SaveChangesAsync();
@@ -862,7 +921,8 @@ namespace xDataService.EFRepositories {
if ( if (
isSucceed && isSucceed &&
!baseRepositoryEvents.IsNull() !baseRepositoryEvents.IsNull()
) { )
{
baseRepositoryEvents baseRepositoryEvents
.UpdateManyEvent(new XBaseEventModel<IEnumerable<T>>(null)); .UpdateManyEvent(new XBaseEventModel<IEnumerable<T>>(null));
} }
@@ -875,14 +935,18 @@ namespace xDataService.EFRepositories {
// //
#region Count ... #region Count ...
public async Task<int> CountAsync (bool ignoreSoftDeleteds = true) { public async Task<int> CountAsync(bool ignoreSoftDeleteds = true)
{
// //
var dbSet = GetDbSet(); var dbSet = GetDbSet();
// //
if (ignoreSoftDeleteds && configuration.EnableSoftDelete) { if (ignoreSoftDeleteds && configuration.EnableSoftDelete)
{
return await dbSet.CountAsync(i => i.Deleted == false); return await dbSet.CountAsync(i => i.Deleted == false);
} else { }
else
{
return await dbSet.CountAsync(); return await dbSet.CountAsync();
} }
} }
@@ -890,13 +954,15 @@ namespace xDataService.EFRepositories {
public async Task<int> PagesCountAsync( public async Task<int> PagesCountAsync(
int pageSize, int pageSize,
int? totalItems = null int? totalItems = null
) { )
{
// //
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(); int count = totalItems.HasValue ? totalItems.Value : await CountAsync();
int pagesCount = count / pageSize; int pagesCount = count / pageSize;
// //
if (count % pageSize > 0) { if (count % pageSize > 0)
{
pagesCount++; pagesCount++;
} }
@@ -910,7 +976,8 @@ namespace xDataService.EFRepositories {
public async Task<bool> IsExistsAsync( public async Task<bool> IsExistsAsync(
TKey id, TKey id,
bool ignoreSoftDeleteds = true bool ignoreSoftDeleteds = true
) { )
{
// //
var result = await FindOneAsync(i => var result = await FindOneAsync(i =>
GetKey(i) GetKey(i)
@@ -930,7 +997,8 @@ namespace xDataService.EFRepositories {
// //
#region Unit Of Work ... #region Unit Of Work ...
public async Task<int> SaveChangesAsync () { public async Task<int> SaveChangesAsync()
{
return await unitOfWorks.SaveChangesAsync(); return await unitOfWorks.SaveChangesAsync();
} }
#endregion #endregion
@@ -940,11 +1008,13 @@ namespace xDataService.EFRepositories {
public void SetKey( public void SetKey(
ref T item, ref T item,
TKey id TKey id
) { )
{
// //
var props = item.GetType().GetProperties(); var props = item.GetType().GetProperties();
var keyProp = props.FirstOrDefault(p => p.Name == "Id"); var keyProp = props.FirstOrDefault(p => p.Name == "Id");
if (keyProp.IsNull ()) { if (keyProp.IsNull())
{
return; return;
} }
@@ -954,27 +1024,33 @@ namespace xDataService.EFRepositories {
keyProp.SetValue(item, safeValue, null); keyProp.SetValue(item, safeValue, null);
} }
public TKey GetKey (T item) { public TKey GetKey(T item)
{
// //
var props = item.GetType().GetProperties(); var props = item.GetType().GetProperties();
var keyProp = props.FirstOrDefault(p => p.Name == "Id"); var keyProp = props.FirstOrDefault(p => p.Name == "Id");
// //
var keyString = string.Empty; var keyString = string.Empty;
if (keyProp.IsNull ()) { if (keyProp.IsNull())
{
keyString = string.Empty; keyString = string.Empty;
} else { }
else
{
keyString = keyProp.GetValue(item).ToString(); keyString = keyProp.GetValue(item).ToString();
} }
// //
if (keyString.IsNullOrEmpty ()) { if (keyString.IsNullOrEmpty())
{
return default(TKey); return default(TKey);
} }
// //
// Prevent Deserializing issues throug JsonReader ... // Prevent Deserializing issues throug JsonReader ...
if (keyString.IsGuid () && typeof (TKey) == typeof (Guid)) { if (keyString.IsGuid() && typeof(TKey) == typeof(Guid))
{
return item.Id; return item.Id;
} }
@@ -982,7 +1058,8 @@ namespace xDataService.EFRepositories {
return keyString.FromJSON<TKey>(); return keyString.FromJSON<TKey>();
} }
public async Task<T> HandleKeyAsync (T item) { public async Task<T> HandleKeyAsync(T item)
{
// //
var keyType = typeof(TKey); var keyType = typeof(TKey);
@@ -995,7 +1072,8 @@ namespace xDataService.EFRepositories {
keyType == typeof(string) keyType == typeof(string)
) && ) &&
keyGenerator.IsEmpty(item.Id) keyGenerator.IsEmpty(item.Id)
) { )
{
// //
var newKey = await keyGenerator.GenerateKey(this); var newKey = await keyGenerator.GenerateKey(this);
@@ -1010,9 +1088,11 @@ namespace xDataService.EFRepositories {
// //
#region Detach ... #region Detach ...
public void Detach (T item) { public void Detach(T item)
{
// //
if (item.IsNull ()) { if (item.IsNull())
{
return; return;
} }
@@ -1020,23 +1100,28 @@ namespace xDataService.EFRepositories {
Entry(item).State = EntityState.Detached; Entry(item).State = EntityState.Detached;
} }
public void Detach (IEnumerable<T> items) { public void Detach(IEnumerable<T> items)
{
// //
if (items.IsNull () || !items.HasChild ()) { if (items.IsNull() || !items.HasChild())
{
return; return;
} }
// //
items items
.ToList() .ToList()
.ForEach (item => { .ForEach(item =>
{
Detach(item); Detach(item);
}); });
} }
public void Detach (XQueryResult<T> query) { public void Detach(XQueryResult<T> query)
{
// //
if (query.IsNull () || query.Items.HasChild ()) { if (query.IsNull() || query.Items.HasChild())
{
return; return;
} }
@@ -1044,9 +1129,11 @@ namespace xDataService.EFRepositories {
Detach(query.Items); Detach(query.Items);
} }
public void Detach (XPageResponse<T> page) { public void Detach(XPageResponse<T> page)
{
// //
if (page.IsNull () || !page.Nodes.HasChild ()) { if (page.IsNull() || !page.Nodes.HasChild())
{
return; return;
} }
@@ -1057,11 +1144,13 @@ namespace xDataService.EFRepositories {
// //
#region Others ... #region Others ...
public void Dispose () { public void Dispose()
{
unitOfWorks.Dispose(); unitOfWorks.Dispose();
} }
public string GetPropValues (T item) { public string GetPropValues(T item)
{
// //
var props = item.GetType().GetProperties(); var props = item.GetType().GetProperties();
var vals = props.Select(p => p.GetValue(p.Name)); var vals = props.Select(p => p.GetValue(p.Name));
@@ -1070,18 +1159,23 @@ namespace xDataService.EFRepositories {
return vals.ToJSON(); return vals.ToJSON();
} }
public EntityEntry<T> Entry (T item) { public EntityEntry<T> Entry(T item)
{
return unitOfWorks.DbContext.Entry(item); return unitOfWorks.DbContext.Entry(item);
} }
public IQueryable<T> GetDbSet( public IQueryable<T> GetDbSet(
bool containsDetail = false bool containsDetail = false
) { )
{
// //
IQueryable<T> result = null; IQueryable<T> result = null;
if (!containsDetail) { if (!containsDetail)
{
result = dbSet; result = dbSet;
} else { }
else
{
result = GetFullDbSet(); result = GetFullDbSet();
} }