Generics and LINQ to XML

I need to create a generic xmlRepository where I can pass any type and return a list.

At the moment, my code looks like this: (The only way I can make it work):

public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
{
    var filename = GetEntityFileName<TEntity>();
    var doc = XDocument.Load(filename);
    var query = (from p in doc.Descendants(entityName)
                 select (ServiceAccount)p).AsQueryable().Cast<TEntity>();
    return query;
}

I would like to change

select (ServiceAccount)p).AsQueryable().Cast<TEntity>();

with

select (TEntity)p).AsQueryable();

TEntity is the same object as ServiceAccount,

Is this possible with LINQ to XML?

I have an SQLRepository using EF that has the same method in it, and I'm looking for the equivalent of LINQ to XML

((IObjectContextAdapter)_context).ObjectContext.CreateQuery<TEntity>(entityName);

If there really is one.

+3
source share
2 answers

You need to specify how you are going to convert XElementto an instance T. Currently, your code just doesn't work if it ServiceAccountalready has an explicit conversion from XElement.

, FromXElement - :

private static readonly Dictionary<Type, Delegate> Converters =
    new Dictionary<Type, Delegate> {
        { typeof(ServiceAccount),
          (Func<XElement, ServiceAccount>) ServiceAccount.FromXElement },
        { typeof(OtherEntity),
          (Func<XElement, OtherEntity>) OtherEntity.FromXElement },
    };

- :

public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
{
    Delegate converter;
    if (!Converters.TryGetValue(typeof(TEntity), out converter))
    {
        throw new InvalidOperationException("...");
    }
    Func<XElement, TEntity> realConverter = (Func<XElement, TEntity>) converter;

    var filename = GetEntityFileName<TEntity>();
    var doc = XDocument.Load(filename);
    return doc.Descendants(entityName)
              .Select(realConverter)
              .AsQueryable();
}

, IQueryable<T> , ... - IEnumerable<T>?

+3

p XElement, ?

ServiceAccount . ?

?

, TEntity : class.

0

All Articles