为要保存为UTC的DateTime创建自定义属性实体框架5

问题描述 投票:0回答:2

我正在尝试使用本文提供的代码

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));
    }
}

}

但是我遇到了一个错误

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

错误:非泛型方法'System.Reflection.MemberInfo.GetCustomAttributes(bool)'不能与类型参数一起使用

任何解决方案???

c# entity-framework asp.net-mvc-4 datetime entity-framework-5
2个回答
2
投票

使用您发布的代码,我希望这样:

'System.Reflection.PropertyInfo'不包含针对 “ GetCustomAttribute”,没有扩展方法“ GetCustomAttribute” 接受类型为'System.Reflection.PropertyInfo'的第一个参数 可以找到

如果您将代码更改为此(即,将通话复数)

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

然后,您将收到发布的错误:

非泛型方法 'System.Reflection.MemberInfo.GetCustomAttributes(bool)'不能为 与类型参数一起使用

原始答案中使用的通用方法是CustomAttributeExtensions名称空间的扩展,并且您需要.NET 4.5


0
投票

只是有同样的问题,我的解决方案只是添加

using System.Reflection;
© www.soinside.com 2019 - 2024. All rights reserved.