CodeLiturgy.Dashboard/BlueWest.Domain/Templates/AddToListTemplate.csx

26 lines
1.3 KiB
Plaintext
Raw Normal View History

2022-09-08 06:15:44 +03:00
/// <summary>
/// Adds a new item into {listPropertyName} from {entityTypeName}.
/// </summary>
/// <param name="dbContext">The database context.</param>
/// <param name="{primaryKeyVarName}">The {entityTypeName} key to get</param>
/// <param name="{listItemCreateVarName}">The item to add to {listPropertyName}.</param>
/// <returns>The success of the operation, a message, and a projection of the added item. </returns>
public static (bool, string, {returnTypeFullName}) Add{listEntityTypeName}To{entityTypeName}(this {contextFullName} dbContext,
{primaryKeyFullName} {primaryKeyVarName}, {listEntityCreateFullName} {listItemCreateVarName})
2022-09-01 08:54:42 +03:00
{
var entityQuery = from aEntity in dbContext.{propertyName}
2022-09-08 06:15:44 +03:00
where aEntity.{primaryKeyPropertyName} == {primaryKeyVarName}
let itemsInList = aEntity.{listPropertyName}
2022-09-01 08:54:42 +03:00
select aEntity;
var entity = entityQuery.FirstOrDefault();
2022-09-08 06:15:44 +03:00
if (entity == null) return (false, $"{entityTypeName} Not found.", null);
2022-09-01 08:54:42 +03:00
var newListItem = new {listEntityFullName}({listItemCreateVarName});
2022-09-08 06:15:44 +03:00
entity.{listPropertyName}.Add(newListItem);
2022-09-01 08:54:42 +03:00
var success = dbContext.SaveChanges() >= 0;
2022-09-08 06:15:44 +03:00
return !success ? (false, "Error saving changes in the Database. Action: Create {listEntityTypeName} in {entityTypeName}.", null) :
(true, string.Empty, new {returnTypeFullName}(newListItem));
2022-09-01 08:54:42 +03:00
}