1

I'm trying to use the code given in this article

Entity Framework DateTime and UTC

[AttributeUsage(AttributeTargets.Property)]
public class DateTimeKindAttribute : Attribute
{
private readonly DateTimeKind _kind;

public DateTimeKindAttribute(DateTimeKind kind)
{
    _kind = kind;
}

public DateTimeKind Kind
{
    get { return _kind; }
}

public static void Apply(object entity)
{
    if (entity == null)
        return;

    var properties = entity.GetType().GetProperties()
        .Where(x => x.PropertyType == typeof(DateTime) || x.PropertyType == typeof(DateTime?));

    foreach (var property in properties)
    {
        var attr = property.GetCustomAttribute<DateTimeKindAttribute>();
        if (attr == null)
            continue;

        var dt = property.PropertyType == typeof(DateTime?)
            ? (DateTime?) property.GetValue(entity)
            : (DateTime) property.GetValue(entity);

        if (dt == null)
            continue;

        property.SetValue(entity, DateTime.SpecifyKind(dt.Value, attr.Kind));
    }
}

}

But I'm getting an error at

var attr = property.GetCustomAttribute<DateTimeKindAttribute>();

Error : The non-generic method 'System.Reflection.MemberInfo.GetCustomAttributes(bool)' cannot be used with type arguments

Any solutions???

Community
  • 1
  • 1
hendrixchord
  • 4,662
  • 4
  • 25
  • 39

2 Answers2

3

Just had the same problem, my solution was simply to add

using System.Reflection;
zevele
  • 46
  • 1
  • 3
2

With the code you posted, I would expect this:

'System.Reflection.PropertyInfo' does not contain a definition for 'GetCustomAttribute' and no extension method 'GetCustomAttribute' accepting a first argument of type 'System.Reflection.PropertyInfo' could be found

If you changed the code to this (i.e. make the call plural)

var attr = property.GetCustomAttributes<DateTimeKindAttribute>();

then you get the error you posted:

The non-generic method 'System.Reflection.MemberInfo.GetCustomAttributes(bool)' cannot be used with type arguments

The generic method used in the original answer is an extension in the CustomAttributeExtensions namespace, and you need .NET 4.5

Colin
  • 22,328
  • 17
  • 103
  • 197