CodeLiturgy.Dashboard/BlueWest.Api/Context/Templates/AddToListTemplate.csx

26 lines
1.3 KiB
C#

public static (bool, string, {returnTypeFullName}) Add{listEntityTypeName}To{entityTypeName}( this {contextFullName} dbContext,
{keyTypeFullName} {keyVarName}, {listEntityCreateFullName} {listItemCreateVarName}, Expression<Func<{entityTypeFullName},bool>>[] duplicationValidations)
{
var entityQuery = from aEntity in dbContext.{propertyName}
where aEntity.{keyVarName} == {keyVarName}
let itemsInList = aEntity.{entityListMemberName}
select aEntity;
var entity = entityQuery.FirstOrDefault();
if (entity == null) return (false, $"{nameof(country)} Not found.", null);
foreach (var duplicationValidation in duplicationValidations)
{
var entityToGet = dbContext.{entityListMemberName}.FirstOrDefault(duplicationValidation);
if (entityToGet != null)
{
return (false, $"Duplication Validation failed: {nameof(duplicationValidation.Body.ToString)}", null);
}
}
var newListItem = new {listEntityFullName}({listItemCreateVarName});
entity.{entityListMemberName}.Add({listItemCreateVarName});
var success = dbContext.SaveChanges() >= 0;
return !success ? (false, "Error saving changes.", null) : (true, string.Empty, new {returnTypeFullName}(newListItem));
}