如何在linq表上确定运行时的延迟加载属性?

时间:2010-08-03 15:04:24

标签: linq-to-sql reflection lazy-loading

我在我的代码中迭代各种映射表的属性,并且需要知道每个属性是否都是延迟加载的。我发现用于存储的实例变量(由属性上的Storage属性表示)将为System.Data.Linq.Link类型。

有没有办法可以在运行时利用这两个事实来解决这个问题?

代码:

public void LazyLoad(Type tableType)
{
    foreach (var prop in tableType.GetGenericArguments()[0].GetProperties())
    {
        if (/* IS LAZY LOADED */)
        {
            //real work here...
            Console.WriteLine(prop.Name);
        }
    }
}

映射看起来像这样:

public partial class Address
{
    private System.Data.Linq.Link<string> _City;

    [Column(Storage="_City", DbType="...")]
    public string City
    {
        get { /* ... */ }
        set { /* ... */ }
    }
}

1 个答案:

答案 0 :(得分:1)

你快到了。只需一把充满反射的勺子就可以帮助药物消失; - )

private static bool IsLazyLoadedProperty(PropertyInfo property)
{
    var column = property.GetCustomAttributes(typeof(ColumnAttribute), true)[0] 
        as ColumnAttribute;

    var field = property.DeclaringType.GetField(column.Storage, 
        BindingFlags.Instance | BindingFlags.NonPublic);

    if (!field.FieldType.IsGenericType)
    {
        return false;
    }

    return field.FieldType.GetGenericTypeDefinition() == typeof(Link<>);
}