I'm trying to create a Repository for an Object Page.
I would like to have non-generic LINQ queries but can't seem to get them working,
I am only able to create them if they are generic and in a helper class, and please let me know if it is recommended to have this type of function in a Helper Class, let me know the reasoning if so.
public class PageRepository
{
public PageViewModel GetPageById(string oid)
{
using (var db = new AppDbContext())
{
Page page = db.Pages
//This is what I cannot get working
.WhereStatusType(StatusType.Published);
return GetPageView(page);
}
}
//I would like the below to work
//Tried generic (below), also non-generic <Page> but doesn't work
internal static IQueryable<T> WhereStatusType<T>(this IQueryable<T> query, StatusType statusType = StatusType.Published)
where T : Page
{
return query.Where(p => p.StatusType == statusType);
}
}
//Below is working, but don't want it in a helper
public static class PageHelper
{
internal static IQueryable<T> WhereStatusType<T>(this IQueryable<T> query, StatusType statusType = StatusType.Published)
where T : Page
{
return query.Where(p => p.StatusType == statusType);
}
}
When I attempt to make the IQueryable non-generic, I receive the following errors:
public class PageRepository has an issue:
Extension method must be defined in a non-generic static class
Also:
'IQueryable' does not contain a definition for 'WhereStatusType' and no extension method 'WhereStatusType' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)
I'm sure it is a simple solution, thank you for the help. Also, if I am approaching this incorrectly, any advice would be greatly appreciated.
Edit:
While FirstOfDefault() is suggested for the above code, I am also looking to use the function when returning List<PageViewModel> (I may have over-simplified the code/example), for example:
public List<PageViewModel> GetPages()
{
using (var context = new AppDbContext())
{
List<Page> pages = new List<Page>();
pages = context.Pages.AsNoTracking()
.WhereStatusType(StatusType.Published)
.ToList();
if (pages != null)
{
List<PageViewModel> pageViewModels = new List<PageViewModel>();
foreach (Page p in pages)
pageViewModels.Add(GetPageView(p));
return pageViewModels;
}
else
return null;
}
}
The error message tells you exactly what's going on here. If you want an extension method -- a method whose first parameter uses the this keyword, like your example -- then it needs to be defined in a non-generic static class, like your PageHelper.
If you don't like that approach, you could define a non-extension method, something like this:
public class PageRepository
{
public PageViewModel GetPageById(string oid)
{
using (var db = new AppDbContext())
{
Page page = GetPagesWithStatus(db.Pages, StatusType.Published);
return GetPageView(page);
}
}
internal IQueryable<Page> GetPagesWithStatus(IQueryable<Page> query, StatusType statusType)
{
return query.Where(p => p.StatusType == statusType);
}
}
As #asherber mentioned, your LINQ query isn't right. You are comparing p.Alias to p.Alias
Also, it looks like you want a FirstOrDefault() in there.
Related
In my DB I have tables who have an attribute int DeleteState. I want a generic method to query those tables. In other words a method who does this: Context.Table.Where(x => x.DeleteState == 0).
I thought I could do this:
public static class Extensions
{
public static IQueryable<T> Exists<T>(this IQueryable<T> qry) where T : IDeletable
{
return qry.Where(x => x.DeleteState == 0);
}
}
Where IDeletable is this:
public interface IDeletable
{
int DeleteState { get; set; }
}
Now I only have to add the IDeletable in the EF model:
public partial class Table : EntityObject, IDeletable { ... }
I did this with the templating mechanism.
Unfortunately, it doesn't work :( It compiles fine, but throws at runtime:
Unable to cast the type 'Table' to type 'IDeletable'. LINQ to Entities only supports casting Entity Data Model primitive types
if I call it like that:
Context.Table.Exists();
How can I solve this problem? Could you think of a fix or a different method to achieve similar results? Thx
The problem you have is that the Entity Framework can only work with an Expression Tree. Your function executes a query directly instead of building an Expression Tree.
A simpler solution would be to add a Model Defined Function.
A model defined function can be called directly on an instance of your context.
Maybe:
public static IQueryable<T> Exists<T>(this IQueryable<T> qry)
{
return qry.Where(x => (!typeof(IDeletable).IsAssignableFrom(x.GetType()) || typeof(IDeletable).IsAssignableFrom(x.GetType()) && ((IDeletable)x).DeleteState == 0));
}
Tsss, this is the answer: Linq Entity Framework generic filter method
I forgot about the class here:
... where T : class, IDeletable
Have you tried converting your objects to IDeletable before you actually query? e.g.
public static IQueryable<T> Exists<T>(this IQueryable<T> qry)
{
return qry.Select<T, IDeletable>(x => x).Where(x => x.DeleteState == 0).Cast<T>();
}
I haven't tested this code, however, the error rings a bell and I remember I had to do something similar.
I'm experimenting with linq and generics. For now, I just implemented a GetAll method which returns all records of the given type.
class BaseBL<T> where T : class
{
public IList<T> GetAll()
{
using (TestObjectContext entities = new TestObjectContext(...))
{
var result = from obj in entities.CreateObjectSet<T>() select obj;
return result.ToList();
}
}
}
This works fine. Next, I would like to precompile the query:
class BaseBL<T> where T : class
{
private readonly Func<ObjectContext, IQueryable<T>> cqGetAll =
CompiledQuery.Compile<ObjectContext, IQueryable<T>>(
(ctx) => from obj in ctx.CreateObjectSet<T>() select obj);
public IList<T> GetAll()
{
using (TestObjectContext entities = new TestObjectContext(...))
{
var result = cqGetAll.Invoke(entities);
return result.ToList();
}
}
}
Here, i get the following:
base {System.Exception} = {"LINQ to Entities does not recognize the method
'System.Data.Objects.ObjectSet`1[admin_model.TestEntity] CreateObjectSet[TestEntity]()'
method, and this method cannot be translated into a store expression."}
What is the problem with this? I guess the problem is with the result of the execution of the precompiled query, but I am unable to fanthom why.
I had this exception when I used methods inside the LINQ query that are not part of the entity model. The problem is that the precompiled query can't invoke the CreateObjectSet for the type TestEntity because the precompiled query is not part of the context that is used to invoke it.
I've got a few tables that all have the same column domainID which basically just controls what data gets displayed on which website, as they share a database.
So when I go to databind a table to a control I would need to create a large switch to handle the different LINQ queries. I would like to create a utility method which takes the table type as a parameter and then return a where clause based on a column in passed table.
public static IEnumerable<T> ExecuteInContext<T>(
IQueryable<T> src)
{
int domain = 1;//hard coded for example
return src.Where(x => x.DomainID == domain);//Won't work, has to be a way to do this.
}
I'm stuck on the return code. You can't simply construct a where clause like I currently am because it doesn't know what table i'm talking about.
I'm trying to call that first method like this:
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var q = Utility.ExecuteInContext(db.GetTable<item>());
Repeater1.DataSource = q;
Repeater1.DataBind();
}
I hope this explains what I'm trying to do.
Edit: BrokenGlass's answer solved my problem. I would like to add that you need to open up your .dbml.cs file and extend the table/class with your interface. I also wanted to point out that the project wouldn't build if my column was nullable, it said it wasn't the same return type as my interface.
You have to restrict your T to a class that has a property of DomainID - you can add these interface implementations in partial classes that extend your data model.
public interface IFoo
{
int DomainId { get; set; }
}
..
public static IQueryable<T> ExecuteInContext<T>(IQueryable<T> src) where T: IFoo
{
int domain = 1;//hard coded for example
return src.Where(x => x.DomainID == domain);
}
Expression pe = Expression.Parameter(typeof(T));
Expression prope = Expression.Property(pe, "DomainID");
Expression ce = Expression.Equals(prope,
Expression.Constant((int)1);
Expression<Func<T,bool>> exp =
Expression.Lambda<Func<T,bool>>(
ce, pe);
return query.Where(exp);
You should be able to cast your generic parameter to the intended type...
public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src)
{
int domain = 1;//hard coded for example
return src.Where(x => ((T)x).DomainID == domain);
}
But you realize you've created a generic method that assumes its type parameter will always expose a specific property? If you're going to do that, you should apply a generic type constraint such that T is always derived from a type that has that property...
For example:
public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src) where T : IMyDomainObject
I'm not sure if I understand what you mean, but maybe you want to add a where clause:
public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src)
where T: MyType //MyType exposing your DomainId
{
int domain = 1;//hard coded for example
return src.Where(x => x.DomainID == domain);//Won't work, has to be a way to do this.
}
public IQueryable<T> All()
{
var session = _sessionFactory.GetCurrentSession();
return FilterByClientId(from r in session.Query<T>() select r);
}
public IQueryable<T> FilterByClientId(IQueryable<T> queryable)
{
return queryable.Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
}
Can I make use of Custom Attribute on the method to handle the decoration? the resulting code would look something like this. call to All method with the ClientFilter would automatically decorate the result.
[ClientFilter]
public IQueryable<T> All()
{
var session = _sessionFactory.GetCurrentSession();
return from r in session.Query<T>() select r;
}
You're looking for PostSharp, which allows you to modify method behavior using attributes.
However, it will add tremendous complexity and probably isn't worth it for something this simple.
If I understand what you are asking, then the answer is probably yes, but the complication of using attributes isn't worth it. Wouldn't it be simpler to make your second code sample simply be as follows?
// Edited to make more sense, but see below...
public IQueryable<T> FilterByClientId()
{
return All().Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
}
EDIT: Based on your comment, try defining FilterByClientId as an extension method with a generic constraint:
public static IQueryable<T> FilterByClientId(this IQueryable<T> queryable) where T : IHasClientId
{
return queryable.Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
}
I'm trying to create a generic repository for my models. Currently i've 3 different models which have no relationship between them. (Contacts, Notes, Reminders).
class Repository<T> where T:class
{
public IQueryable<T> SearchExact(string keyword)
{
//Is there a way i can make the below line generic
//return db.ContactModels.Where(i => i.Name == keyword)
//I also tried db.GetTable<T>().Where(i => i.Name == keyword)
//But the variable i doesn't have the Name property since it would know it only in the runtime
//db also has a method ITable GetTable(Type modelType) but don't think if that would help me
}
}
In MainViewModel, I call the Search method like this:
Repository<ContactModel> _contactRepository = new Repository<ContactModel>();
public void Search(string keyword)
{
var filteredList = _contactRepository.SearchExact(keyword).ToList();
}
Solution:
Finally went with Ray's Dynamic Expression solution:
public IQueryable<TModel> SearchExact(string searchKeyword, string columnName)
{
ParameterExpression param = Expression.Parameter(typeof(TModel), "i");
Expression left = Expression.Property(param, typeof(TModel).GetProperty(columnName));
Expression right = Expression.Constant(searchKeyword);
Expression expr = Expression.Equal(left, right);
}
query = db.GetTable<TModel>().Where(Expression.Lambda<Func<TModel, bool>>(expr, param));
Interface solution
If you can add an interface to your object you can use that. For example you could define:
public interface IName
{
string Name { get; }
}
Then your repository could be declared as:
class Repository<T> where T:class, IName
{
public IQueryable<T> SearchExact(string keyword)
{
return db.GetTable<T>().Where(i => i.Name == keyword);
}
}
Alternate interface solution
Alternatively you could put the "where" on your SearchExact method by using a second generic parameter:
class Repository<T> where T:class
{
public IQueryable<T> SearchExact<U>(string keyword) where U: T,IName
{
return db.GetTable<U>().Where(i => i.Name == keyword);
}
}
This allows the Repository class to be used with objects that don't implement IName, whereas the SearchExact method can only be used with objects that implement IName.
Reflection solution
If you can't add an IName-like interface to your objects, you can use reflection instead:
class Repository<T> where T:class
{
static PropertyInfo _nameProperty = typeof(T).GetProperty("Name");
public IQueryable<T> SearchExact(string keyword)
{
return db.GetTable<T>().Where(i => (string)_nameProperty.GetValue(i) == keyword);
}
}
This is slower than using an interface, but sometimes it is the only way.
More notes on interface solution and why you might use it
In your comment you mention that you can't use an interface but don't explain why. You say "Nothing in common is present in the three models. So i think making an interface out of them is not possible." From your question I understood that all three models have a "Name" property. In that case, it is possible to implement an interface on all three. Just implement the interface as shown and ", IName" to each of your three class definitions. This will give you the best performance for both local queries and SQL generation.
Even if the properties in question are not all called "Name", you can still use the nterface solution by adding a "Name" property to each and having its getter and setter access the other property.
Expression solution
If the IName solution won't work and you need the SQL conversion to work, you can do this by building your LINQ query using Expressions. This more work and is significantly less efficient for local use but will convert to SQL well. The code would be something like this:
class Repository<T> where T:Class
{
public IQueryable<T> SearchExact(string keyword,
Expression<Func<T,string>> getNameExpression)
{
var param = Expression.Parameter(typeof(T), "i");
return db.GetTable<T>().Where(
Expression.Lambda<Func<T,bool>>(
Expression.Equal(
Expression.Invoke(
Expression.Constant(getNameExpression),
param),
Expression.Constant(keyword),
param));
}
}
and it would be called thusly:
repository.SearchExact("Text To Find", i => i.Name)
Ray's method is quite good, and if you have the ability to add an interface definitely the superior however if for some reason you are unable to add an interface to these classes (Part of a class library you can't edit or something) then you could also consider passing a Func in which could tell it how to get the name.
EG:
class Repository<T>
{
public IQueryable<T> SearchExact(string keyword, Func<T, string> getSearchField)
{
return db.GetTable<T>().Where(i => getSearchField(i) == keyword);
}
}
You'd then have to call it as:
var filteredList = _contactRepository.SearchExact(keyword, cr => cr.Name).ToList();
Other than these two options you could always look into using reflection to access the Name property without any interface, but this has the downside that there's no compile-time check that makes sure the classes you're passing actually DO have a Name property and also has the side-effect that the LINQ will not be translated to SQL and the filtering will happen in .NET (Meaning the SQL server could get hit more than is needed).
You could also use a Dynamic LINQ query to achieve this SQL-side effect, but it has the same non type-safe issues listed above.