Skip to content

String is Unicode Attribute #5

@ChrisReddickClarity

Description

@ChrisReddickClarity

Here's another attribute you can add to this library:

/// <summary>Attribute for string is unicode. This class cannot be inherited.</summary>
/// <seealso cref="T:System.Attribute"/>
[AttributeUsage(AttributeTargets.Property)]
public sealed class StringIsUnicodeAttribute : Attribute
{
    /// <summary>Initializes a new instance of the <see cref="StringIsUnicodeAttribute"/> class.</summary>
    /// <param name="isUnicode">true if this object is unicode, false if not.</param>
    public StringIsUnicodeAttribute(bool isUnicode)
    {
        IsUnicode = isUnicode;
    }

    /// <summary>Gets a value indicating whether this object is unicode.</summary>
    /// <value>true if this object is unicode, false if not.</value>
    public bool IsUnicode { get; }
}

And here's how I'm implementing it with my modelBuilder, you would need to convert this to your Convention methodology:

private static void ImplementStringIsUnicodeAttributes(DbModelBuilder modelBuilder)
{
    // Implement String Is Unicode Attributes
    foreach (var classType in Assembly.GetAssembly(typeof(StringIsUnicodeAttribute))
                                .GetTypes()
                                .Where(t => t.IsClass && t.Namespace == "YOUR.NAMESPACE"))
    {
        foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                    .Where(p => p.GetCustomAttribute<StringIsUnicodeAttribute>() != null)
                                    .Select(p => new { prop = p, attr = p.GetCustomAttribute<StringIsUnicodeAttribute>(true) }))
        {
            var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
            var param = Expression.Parameter(classType, "c");
            var property = Expression.Property(param, propAttr.prop.Name);
            var lambdaExpression = Expression.Lambda(property, true, param);
            var methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[4];
            var stringConfig = methodInfo.Invoke(entityConfig, new object[] { lambdaExpression }) as StringPropertyConfiguration;
            stringConfig?.IsUnicode(propAttr.attr.IsUnicode);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions