开发者

LINQ Generic Query with inherited base class?

开发者 https://www.devze.com 2022-12-25 19:24 出处:网络
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 objec

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:

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 开发者_StackOverflowbecause 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'.  

=(


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消