Mango.Nop.Libraries/Mango.Nop.Core/Extensions/GenericAttributeExtensions.cs

53 lines
1.7 KiB
C#

using System;
using System.Collections.Generic;
using AyCode.Utils.Extensions;
using Mango.Nop.Core.Utils;
using Nop.Core.Domain.Common;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Mango.Nop.Core.Extensions;
public static class GenericAttributeExtensions
{
public static TValue? GetValueOrNull<TValue>(this IEnumerable<GenericAttribute> src, string key) where TValue : struct
{
var ga = src.SingleOrDefault(x => x.Key == key);
if (ga == null || ga.Value.IsNullOrWhiteSpace()) return null;
return CommonHelper2.To<TValue>(ga.Value);
}
public static TValue GetValueOrDefault<TValue>(this IEnumerable<GenericAttribute> src, string key, TValue defaultValue = default) where TValue : struct
{
var gaValue = GetValueOrNull<TValue>(src, key);
return gaValue == null ? defaultValue : CommonHelper2.To<TValue>(gaValue);
}
public static bool TryGetValue<TValue>(this IEnumerable<GenericAttribute> src, string key, [NotNullWhen(true)] out TValue? value) where TValue : struct
{
value = null;
var gaValue = GetValueOrNull<TValue>(src, key);
if (gaValue == null) return false;
value = CommonHelper2.To<TValue>(gaValue);
return true;
}
public static GenericAttribute AddNewGenericAttribute(this ICollection<GenericAttribute> src, string keyGroup, string key, string value, int entityId, int storeId)
{
var ga = new GenericAttribute
{
KeyGroup = keyGroup,
Key = key,
Value = value,
EntityId = entityId,
StoreId = storeId,
CreatedOrUpdatedDateUTC = DateTime.UtcNow
};
src.Add(ga);
return ga;
}
}