mercredi 12 avril 2017

How can I sort by primary key or any default value to allow me to Skip and Take in EF on a generic collection?

I have a method that takes IQueryable<T> and I do a bunch of generic stuff on it. Usually the order property will be specified which is fine but sometimes nothing is provided, and I need to order it by something in order to apply skip/take.

I'd be happiest doing this on the primary key, but anything that will work is also good.

I can't seem to get the primary key from the IQueryable<T> collection though. I tried some code I found online to loop through PropertyInfo[] properties = typeof(T).GetProperties(); properties and GetCustomAttributes() but there didn't seem to be any attributes at all.

I was using this method but it just gave me null:

private PropertyInfo GetPrimaryKeyInfo<T>()
{
    PropertyInfo[] properties = typeof(T).GetProperties();
    foreach (PropertyInfo pI in properties)
    {
        System.Object[] attributes = pI.GetCustomAttributes(true);
        foreach (object attribute in attributes)
        {
            if (attribute is EdmScalarPropertyAttribute)
            {
                if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                    return pI;
            }
            else if (attribute is System.Data.Linq.Mapping.ColumnAttribute)
            {

                if ((attribute as System.Data.Linq.Mapping.ColumnAttribute).IsPrimaryKey == true)
                    return pI;
            }
        }
    }
    return null;
}

I can see in my Entity Model that for the instance of T I am using there is a primary key set.

Can anyone advise?





Aucun commentaire:

Enregistrer un commentaire