Files

153 lines
4.8 KiB
C#

using System;
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>
{
//
#region Properties ...
/// <summary>
/// Holds Entity Name ...
/// </summary>
public string Entity { get; }
/// <summary>
/// Holds Database Name ...
/// </summary>
public string Database { get; }
/// <summary>
/// Repository Service for Data Manipulation ...
/// </summary>
public IXBaseRepository<TEntity, TKey> Repository { get; }
/// <summary>
/// DataServiceConfiguration ...
/// </summary>
public XDataServiceConfiguration DataServiceConfiguration { get; }
#endregion
//
#region Constructor ...
public XBaseDbSeeder(
string entity,
string database,
IXBaseRepository<TEntity, TKey> repository,
XDataServiceConfiguration dataServiceConfiguration
)
{
//
this.Entity = entity;
this.Database = database;
this.Repository = repository;
this.DataServiceConfiguration = dataServiceConfiguration;
}
#endregion
public async Task Seed()
{
//
// Validate Seed ...
var isValid =
DataServiceConfiguration.SeedingMode != XDbSeedingMode.None &&
DataServiceConfiguration
.Databases
.Any(db =>
db.Key == Database &&
db.Value.SeedItems
.Any(si =>
si.Key == Entity &&
si.Value.HasChild()));
if (!isValid)
{
return;
}
//
// Extract Seeding Items ...
var seedItems = DataServiceConfiguration
.Databases[Database]
.SeedItems[Entity]
.ToList();
foreach (var item in seedItems)
{
//
try
{
//
var entity = item
.ToJSON()
.FromJSON<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(
item: entity,
saveChanges: true
);
}
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
{ }
}
}
}
}