129 lines
4.2 KiB
C#
129 lines
4.2 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using xCommons.Extensions;
|
|
using xDataService.Configuration;
|
|
using xDataService.Constants;
|
|
using xDataService.Interfaces;
|
|
using xModels.Base;
|
|
|
|
namespace xDataService.Providers
|
|
{
|
|
public abstract class XBaseDbSeeder<TEntity, TKey> : IXBaseDbSeeder<TEntity, TKey>
|
|
where TEntity : XBaseEntity<TKey>
|
|
{
|
|
public string Database { get; }
|
|
|
|
public IXBaseRepository<TEntity, TKey> Repository { get; }
|
|
|
|
public XDataServiceConfiguration DataServiceConfiguration { get; }
|
|
|
|
public XBaseDbSeeder(
|
|
string database,
|
|
IXBaseRepository<TEntity, TKey> repository,
|
|
XDataServiceConfiguration dataServiceConfiguration
|
|
)
|
|
{
|
|
//
|
|
this.Database = database;
|
|
this.Repository = repository;
|
|
this.DataServiceConfiguration = dataServiceConfiguration;
|
|
}
|
|
|
|
public async Task Seed()
|
|
{
|
|
//
|
|
var entityName = nameof(TEntity);
|
|
|
|
//
|
|
// Validate Seed ...
|
|
var isValid =
|
|
DataServiceConfiguration.SeedingMode != XDbSeedingMode.None &&
|
|
DataServiceConfiguration
|
|
.Databases
|
|
.Any(db =>
|
|
db.Key == Database &&
|
|
db.Value.SeedItems
|
|
.Any(si =>
|
|
si.Key == entityName &&
|
|
si.Value.HasChild()));
|
|
if (!isValid)
|
|
{
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Extract Seeding Items ...
|
|
var seedItems = DataServiceConfiguration
|
|
.Databases[Database]
|
|
.SeedItems[entityName]
|
|
.ToList();
|
|
foreach (var item in seedItems)
|
|
{
|
|
//
|
|
try
|
|
{
|
|
//
|
|
// Try to convert Item to Entity ...
|
|
var entity = ((object)item).FromDynamicObject<TEntity>();
|
|
|
|
//
|
|
// Check Item Exists or not ...
|
|
var isExist = false;
|
|
TEntity exists = null;
|
|
var asyncEnumerable = this.Repository.GetAllAsAsyncEnumerable();
|
|
await foreach (var e in asyncEnumerable)
|
|
{
|
|
//
|
|
isExist = e.IsSameContent(
|
|
dest: entity,
|
|
propertyBlackList: new List<string>
|
|
{
|
|
nameof(entity.Id),
|
|
nameof(entity.Deleted)
|
|
});
|
|
if (isExist)
|
|
{
|
|
exists = e;
|
|
break;
|
|
}
|
|
}
|
|
|
|
//
|
|
// Seed Based on Seed Mode ...
|
|
var seedMode = DataServiceConfiguration.SeedingMode;
|
|
switch (seedMode)
|
|
{
|
|
//
|
|
case XDbSeedingMode.AddIfNotExists:
|
|
//
|
|
if (!isExist)
|
|
{
|
|
//
|
|
exists = await Repository.AddAsync(entity);
|
|
}
|
|
break;
|
|
|
|
//
|
|
case XDbSeedingMode.AddOrUpdate:
|
|
//
|
|
exists = exists.UpdateData(
|
|
updateWith: entity,
|
|
propertyBlackList: new List<string>
|
|
{
|
|
nameof(entity.Id),
|
|
nameof(entity.Deleted)
|
|
}
|
|
);
|
|
|
|
//
|
|
await Repository.AddOrUpdateAsync(exists);
|
|
break;
|
|
}
|
|
}
|
|
catch
|
|
{ }
|
|
}
|
|
}
|
|
}
|
|
} |