Created
November 18, 2013 12:52
-
-
Save wizact/7527296 to your computer and use it in GitHub Desktop.
Resolving EntitySetName and predicate/project automatically for WCF Data Service.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data.Services.Client; | |
using System.Data.Services.Common; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ODataSampleClient | |
{ | |
public class DynamicLookup<T> | |
{ | |
DataServiceContext context; | |
string repositoryName; | |
public DynamicLookup() | |
{ | |
this.context = new DataServiceContext(new Uri("http://localhost:52160/SampleDataService.svc/")); | |
repositoryName = this.ResolveEntitySetName(typeof(T)); | |
} | |
public List<K> Lookup<T, K>(Expression<Func<T, bool>> predicate, Expression<Func<T, K>> projection) | |
{ | |
return this.context.CreateQuery<T>(this.repositoryName).Where<T>(predicate).Select<T, K>(projection).ToList<K>(); | |
} | |
public List<T> Lookup<T>(Expression<Func<T, bool>> predicate) | |
{ | |
return this.context.CreateQuery<T>(this.repositoryName).Where<T>(predicate).ToList<T>(); | |
} | |
public List<T> Lookup<T>() | |
{ | |
return this.context.CreateQuery<T>(this.repositoryName).ToList<T>(); | |
} | |
public List<K> Lookup<T, K>(Expression<Func<T, K>> projection) | |
{ | |
return this.context.CreateQuery<T>(this.repositoryName).Select<T, K>(projection).ToList<K>(); | |
} | |
private string ResolveEntitySetName(Type type) | |
{ | |
var entitySetAttribute = | |
(EntitySetAttribute)type.GetCustomAttributes(typeof(EntitySetAttribute), true).FirstOrDefault(); | |
if (entitySetAttribute != null) | |
{ | |
return entitySetAttribute.EntitySet; | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment