score:0
You can create interface:
public interface IName
{
string Name { get; set; }
}
Then implicitly implement IName
interface in both entities.
public class Bar : IName { ... }
public class Foo : IName { ... }
And then change your method as:
public IList<T> SearchByName<T>(string query, DbSet<T> set)
where T: class, IName
{
var equalsQuery = set.Where(f => f.Name.Equals(query));
var containsQuery = set.Where(f => f.Name.Contains(query)).Take(10); // Don't want too many or else a search for "a" would yield too many results
var result = equalsQuery.Union(containsQuery).ToList();
... // go on to return a view
}
score:0
You could overide your ToString() method and use that in the query
public class foo
{
public string FooName
{
get;
set;
}
public override string ToString()
{
return FooName;
}
}
public class Bar
{
public string BarName
{
get;
set;
}
public override string ToString()
{
return BarName;
}
}
public IList<T> Search<T>(string query, DbSet<T> set)
{
var equalsQuery = set.AsEnumerable().Where(f => f.ToString().Equals(query));
var containsQuery = set.AsEnumerable().Where(f => f.ToString().Contains(query)).Take(10);
var result = equalsQuery.Union(containsQuery).ToList(); . . . // go on to return a view
}
score:1
You can achieve this with Expression<Funt<T,string>>
public IList<T> Search<T>(string query, DbSet<T> set, Expression<Func<T, string>> propExp)
{
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
ConstantExpression someValue = Expression.Constant(query, typeof(string));
MethodCallExpression containsMethodExp =
Expression.Call(propExp.Body, method, someValue);
var e = (Expression<Func<T, bool>>)
Expression.Lambda(containsMethodExp, propExp.Parameters.ToArray());
var containsQuery = set.Where(e).Take(10);
BinaryExpression equalExpression = Expression.Equal(propExp.Body, someValue);
e = (Expression<Func<T, bool>>)
Expression.Lambda(equalExpression, propExp.Parameters.ToArray());
var equalsQuery = set.Where(e);
var result = equalsQuery.Union(containsQuery).ToList();
}
Then you'll call it:
Search ("myValue", fooSet, foo=>foo.FooName);
if you can have a static method, then you could have it as an extension method:
public static IList<T> Search<T>(this DbSet<T> set,
string query, Expression<Func<T, string>> propExp)
And call it:
FooSet.Search ("myValue", foo=>foo.FooName);
score:0
Here's one way to do it.
First you need a helper method to generate the Expression
for you:
private Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue, string operatorName)
{
var parameterExp = Expression.Parameter(typeof(T));
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod(operatorName, new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var methodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<T, bool>>(methodExp, parameterExp);
}
This is how you can use this method, propertyName
would be FooName and BarName:
public IList<T> Search<T>(string propertyName, string query, DbSet<T> set)
{
var equalsQuery = set.Where(GetExpression<T>(propertyName, query, "Equals"));
var containsQuery = set.Where(GetExpression<T>(propertyName, query, "Contains")).Take(10); // Don't want too many or else a search for "a" would yield too many results
var result = equalsQuery.Union(containsQuery).ToList();
return result;
}
Source: stackoverflow.com
Related Articles
- How to solve LINQ to Entity query duplication when the queries only differ by a property?
- Entity Framework Linq Query to List - Error when using contains: Only primitive types, enumeration types and entity types are supported
- How to avoid Query Plan re-compilation when using IEnumerable.Contains in Entity Framework LINQ queries?
- Why is MigrationHistory causing Linq results to differ when specifying only a subset of columns?
- LINQ query returns old results when source list is re-initialized
- Linq to Sql NotSupportedException "The explicit construction of the entity in a query is invalid" when selecting new Type of other Database Table
- Exception raised when using a Linq query with Entity Framework
- Linq sub query when using a repository pattern with EF code first
- When does Entity framework Linq query Hits Sql Databse?
- Getting 'Data source is an invalid type' when binding Linq query to Gridview
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- How to write an efficient LINQ query when searching by both parent and child entity fields
- Using Entity properties in LINQ queries when <T> used, Possible?
- How can I build a LINQ predicate/dynamic.LINQ query based off grid filtering when the grid properties don't have the entity properties?
- One LINQ query to get counts from several entities when using entity framework core
- When selecting new Type - The entity or complex type cannot be constructed in a LINQ to Entities query
- why can I only access the properties of an anonymous type when I add .toList to the end of my linq query
- Entity Framework throws NotSupportedException when casting an entity to its base class in a LINQ query
- Getting InvalidCastException when trying to implement sorting in Entity Framework Code First using Linq
- Proper Linq Query for objects with many to many relation ship generated with code first entity framework
- Completing a linq to entites query of a tri-level entity source
- How to Filter DataGridView when bound to a linq query result that is linked to an EF4 Entity
- Error Object Reference Not found when Record does not found using Linq to Entity my Query attached
- Entity Framework EF Query using LINQ for related Entities - Getting Customers with their orders from specific period of time only
- Entity Framework Code Most First Efficient Linq Query
- Linq query throws entity or complex type cannot be constructed in a linq to entity, even when i remove the class name just using select new { ..}
- Entity Framework Code First - The entity or complex type cannot be constructed in a LINQ to Entities query
- Entity framework linq query Include() multiple children entities
- The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties
- 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
- Retrieving Data from LINQ to SQL in JSON format?
- LINQ select from first list
- Modify the expression tree of IQueryable.Include() to add condition to the join
- LINQ to SQL performance, how to reduce contain parameters
- Linq how to move all values of two columns to another table
- Extension method for Sorting a generic iCollection(Of T)
- How to resolve Lambda Expression
- Join to return multiple columns and using group by Entity Framework
- Can not select information of date in query made before
- Set or Assign a value in a Nested generic collection using LinQ C#
- Associate a list to other class MVC (LINQ?)
- having clause after group by on List<object>
- NHibernate QueryOver can't query lazily loaded objects
- How to use LINQ to get unique columns from a DataTable
- LINQ (or) Using processing in loop? What to choose?
- How to get all Objects from a List in a List with LINQ
- Sum TimeSpan by extension method simplification
- Pass aggregate function as parameter
- Linq & ASP.NET MVC: how to use "or" and "equals" in join statement
- How to write EF in linq to include comparison by lower case