views:

330

answers:

1

I am trying to write some generic LINQ queries for my entities, but am having issue doing the more complex things. Right now I am using an EntityDao class that has all my generics and each of my object class Daos (such as Accomplishments Dao) inherit it, am example:

using LCFVB.ObjectsNS;
using LCFVB.EntityNS;

namespace AccomplishmentNS
{
  public class AccomplishmentDao : EntityDao<Accomplishment>{}
}

Now my entityDao has the following code:

using LCFVB.ObjectsNS;
using LCFVB.LinqDataContextNS;

namespace EntityNS
{
public abstract class EntityDao<ImplementationType> where ImplementationType : Entity
{
public ImplementationType getOneByValueOfProperty(string getProperty, object getValue)
{ 
  ImplementationType entity = null;
         if (getProperty != null && getValue != null) {
            //Nhibernate Example:
            //ImplementationType entity = default(ImplementationType);
            //entity = Me.session.CreateCriteria(Of ImplementationType)().Add(Expression.Eq(getProperty, getValue)).UniqueResult(Of InterfaceType)()

            LCFDataContext lcfdatacontext = new LCFDataContext();

            //Generic LINQ Query Here
            lcfdatacontext.GetTable<ImplementationType>();


            lcfdatacontext.SubmitChanges();

            lcfdatacontext.Dispose();
        }


        return entity;
    }

    public bool insertRow(ImplementationType entity)
    {
        if (entity != null) {
            //Nhibernate Example:
            //Me.session.Save(entity, entity.Id)
            //Me.session.Flush()

            LCFDataContext lcfdatacontext = new LCFDataContext();

            //Generic LINQ Query Here
            lcfdatacontext.GetTable<ImplementationType>().InsertOnSubmit(entity);

            lcfdatacontext.SubmitChanges();
            lcfdatacontext.Dispose();

            return true;
        }
        else {
            return false;
        }
    }

}

}

            I have gotten the insertRow function working, however I am not even sure how to go about doing getOnebyValueOfProperty, the closest thing I could find on this site was:

http://stackoverflow.com/questions/2157560/generic-linq-to-sql-query

How can I pass in the column name and the value I am checking against generically using my current set-up? It seems like from that link it's impossible since using a where predicate because entity class doesn't know what any of the properties are until I pass them in.

Lastly, I need some way of setting a new object as the return type set to the implementation type, in nhibernate (what I am trying to convert from) it was simply this line that did it:

  ImplentationType entity = default(ImplentationType);

However default is an nhibernate command, how would I do this for LINQ?

EDIT:

getOne doesn't seem to work even when just going off the base class (this is a partial class of the auto generated LINQ classes). I even removed the generics. I tried:

namespace ObjectsNS
{    
    public partial class Accomplishment
     {
       public Accomplishment getOneByWhereClause(Expression<Action<Accomplishment, bool>> singleOrDefaultClause)
     {
        Accomplishment entity = new Accomplishment();
         if (singleOrDefaultClause != null) {
              LCFDataContext lcfdatacontext = new LCFDataContext();

                 //Generic LINQ Query Here
              entity = lcfdatacontext.Accomplishments.SingleOrDefault(singleOrDefaultClause);

               lcfdatacontext.Dispose();
               }
            return entity;
               }
          }
      }

Get the following error:

Error   1   Overload resolution failed because no accessible 'SingleOrDefault' can be called with these arguments:
Extension method 'Public Function SingleOrDefault(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Accomplishment, Boolean))) As Accomplishment' defined in 'System.Linq.Queryable': Value of type 'System.Action(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))' cannot be converted to 'System.Linq.Expressions.Expression(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))'.
Extension method 'Public Function SingleOrDefault(predicate As System.Func(Of Accomplishment, Boolean)) As Accomplishment' defined in 'System.Linq.Enumerable': Value of type 'System.Action(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))' cannot be converted to 'System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean)'.     14  LCF

Okay no problem I changed:

public Accomplishment getOneByWhereClause(Expression<Action<Accomplishment, bool>> singleOrDefaultClause)

to:

public Accomplishment getOneByWhereClause(Expression<Func<Accomplishment, bool>> singleOrDefaultClause)

Error goes away. Alright, but now when I try to call the method via:

Accomplishment accomplishment = new Accomplishment();
var result = accomplishment.getOneByWhereClause(x=>x.Id = 4)

It doesn't work it says x is not declared.

I also tried

 getOne<Accomplishment>
 Expression<Func<
 Expression<Action<

in various formats, but either the parameters are not recognized correctly as an expression in the function call, or it cannot convert the type I have as the parameter into the type used inside singleofDefault(). So both errors just like above. And the class accomplishment does have the ID. Finally I also tried declaring x as a new accomplishment so it would be declared, at which point the code changes the => to >= automatically and says:

Error   1   Operator '>=' is not defined for types 'LCFVB.ObjectsNS.Accomplishment' and 'Integer'.  

=(

+2  A: 

If I understand what you want the question you linked to describes (sort of) what you need to do.

public ImplementationType getOne(Expression<Func<ImplementationType , bool> singleOrDefaultClause)
{ 
    ImplementationType  entity = null;
    if (singleOrDefaultClause != null) 
    {

        LCFDataContext lcfdatacontext = new LCFDataContext();

        //Generic LINQ Query Here
        entity = lcfdatacontext.GetTable<ImplementationType>().SingleOrDefault(singleOrDefaultClause);


        lcfdatacontext.Dispose();
    }


    return entity;
}

When you call this method it would look something like

//note assumption that ConcreteClass DAO has member called Id
var myEntity = ConcreteClass.getOne(x=>x.Id == myIdVariable);

I haven't compiled this so I can't say it's 100% correct, but the idea works. I'm using something similar except the I defined my methods to be generic with a base class to implement the common code.

Update Can't you just use new to create an instance of the class you need? If you need something more generic then I think you will have to use reflection to invoke the constructor. Sorry if I misunderstood what you were asking.

Update in response to comment for additional details Expansion of updating POCO: There are a lot of ways you can do this but one is to get the PropertyInfo from the expression and invoke the setter. (Probably better ways to do this, but I haven't figured one out.) For example it could look something like:

protected internal bool Update<TRet>(Expression<Func<T, TRet>> property, TRet updatedValue)
{
    var property = ((MemberExpression)member.Body).Member as PropertyInfo;
    if (property != null)
    {
        property.SetValue(this, updatedValue, null);
        return true;
    }
    return false;
}

Note: I pulled this (with some other stuff removed) from my code base on a project I am working. This method is part of a base class that all of my POCOs implement. The Editable base class and the base class for my POCOs are in the same assembly so the Editable can invoke this as an internal method.

I got my methods working but I like yours more because it is more flexible allowing for multiple parameters, but I really really want to keep this in my DAO. It would be kind of confusing to have all db methods in my DAO except one. Would setting the function to be getOne work?

I'm not really sure I understand what you are asking me. Yes you could set the getOne function to be a generic method, this is actually what I have done although I have taken it a step further and all of the methods are generic. This simplified my UI/BL interface boundary and so far at least is expressive/flexibly enough to cover all of my usage requirements without major changes. If it helps I've included the interface that by BL object implements and exposes to the UI. My DAL is essentially NHibernate so I don't have anything to show you there.

public interface ISession : IDisposable
{
    bool CanCreate<T>() where T : class,IModel;
    bool CanDelete<T>() where T : class, IModel;
    bool CanEdit<T>() where T : class, IModel;
    bool CanGet<T>() where T : class, IModel; 

    T Create<T>(IEditable<T> newObject) where T:class,IModel;

    bool Delete<T>(Expression<Func<T, bool>> selectionExpression) where T : class, IModel;

    PageData<T> Get<T>(int page, int numberItemsPerPage, Expression<Func<T, bool>> whereExpression) where T : class, IModel;
    PageData<T> Get<T, TKey>(int page, int numberItemsPerPage, Expression<Func<T, bool>> whereExpression, Expression<Func<T, TKey>> orderBy, bool isAscending) where T : class, IModel;

    T Get<T>(Expression<Func<T, bool>> selectionExpression) where T : class, IModel;

    IEnumerable<T> GetAllMatches<T>(Expression<Func<T, bool>> whereExpression) where T : class, IModel;

    IEditable<T> GetForEdit<T>(Expression<Func<T, bool>> selectionExpression) where T : class, IModel;

    IEditable<T> GetInstance<T>() where T : class, IModel;

    IQueryable<T> Query<T>() where T : class, IModel;

    bool Update<T>(IEditable<T> updatedObject) where T : class, IModel;
}
confusedGeek
Hmmmm is there anyway to do that without passing in the predicate from the function call? That's what I really wanted to avoid. The main issue is because my DAO classes do not have a member called ID. I like to have my object classes separate from database logic classes (DAO) and business logic classes (services).It just seems odd. Is there no expression or .command to signify to input a column name/property as a string?
sah302
confusedGeek
Is it possible to build a predicate off string parameters? I am going to guess no since the id in x.Id is a known property.If possible, then I guess it would just be a two step process of building a predicate off the supplied parameters and then putting that predicate into your example above.
sah302
Oh I think I found an answer to that:http://stackoverflow.com/questions/125400/generic-linq-query-predicate Looks like just what I need, strings as parameters!
sah302
Geek, could you expand upon your Update about using reflection? I got my methods working but I like yours more because it is more flexible allowing for multiple parameters, but I really really want to keep this in my DAO. It would be kind of confusing to have all db methods in my DAO except one. Would setting the function to be getOne<ImplementationType> work?
sah302
@sah302, I've added some additional detail to my answer. Hope this helps.
confusedGeek
Thanks for your response, I apologize if I wasn't being clear, still kind of new to generics and LINQ. Updated my post in response. Is what I am trying to do possible? If not I guess I can just extend the method off the domain object class, but I strongly prefer to keep the concrete class objects separate from the DAOs/services, but I also really realy like the way your function works so would like to use that.
sah302
Also, did you change your original getOne function in an edit? I could have sworn the original contained a <Expression<Action<>> but now I see it's just Expression datatype.
sah302
ok, fixed getOne. Apparently in one of my edits I screwed up the formating and the HTML rendering caused some of the content to not show up.
confusedGeek
getOne doesn't work =(. Tried various forms of it using your getOne exactly, to copying the format of your GetAllMatches, and stuff in between. Edited post with what I tried.
sah302
First error you had, my code had Action instead of Func for some reason, your fix is correct. Was x=>x.Id = 4 a typo (or does code have '=' instead of '==')? Not sure why the last is failing. Note: I'm using these on a class instance other than my Entity objects, although that shouldn't matter in this case.
confusedGeek
Yeah it was a typo. I did have == in the actual code. I figured this out (sort of) I just did this in the function call:'actual == Accomplishment.getOneByWhereClause((Accomplishment x) => x.LocalId == 4). But I am not sure why it can't infer the class as when I input the parameters it says hey yeah this is a expression function with input type as accomplishment.
sah302