Created
February 22, 2015 23:50
-
-
Save hagbarddenstore/299bdea651d54d6bc3aa to your computer and use it in GitHub Desktop.
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.Linq; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var model = new Customer { Id = 1 }; | |
var result = DataService.Exists<Customer, int>(c => model.Id); | |
Console.WriteLine(result); | |
} | |
} | |
public class Customer | |
{ | |
public int Id { get; set; } | |
} | |
public class DataService | |
{ | |
public static bool Exists<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> expression) | |
where TEntity : class | |
{ | |
TProperty value = expression.Compile().Invoke(null); | |
var propertyInfo = ((MemberExpression)expression.Body).Member; | |
var parameter = Expression.Parameter(typeof(TEntity), "entity"); | |
var property = Expression.Property(parameter, propertyInfo.Name); | |
var body = Expression.Equal(property, Expression.Constant(value)); | |
var lambda = Expression.Lambda<Func<TEntity, bool>>(body, parameter); | |
using (var context = new DbContext()) | |
{ | |
return context.Set<TEntity>().Any(lambda); | |
} | |
} | |
} | |
public class DbContext : IDisposable | |
{ | |
public IQueryable<T> Set<T>() | |
{ | |
return new List<T>().AsQueryable(); | |
} | |
public void Dispose() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment