views:

23

answers:

0

I am using LINQ to SQL for my data retrieval. One common fetching scenario is to or fetch by some criteria. The code is below.

public EmployeeRegistrationView FetchByEmailID(IDictionary<string, string> criteria)
        {
            var selEmployeeRegistrationView = from P in db.EmployeeRegistrationViews
                                              where P.EmailID == criteria["EmailID"].ToString()
                                   select P;

            return selEmployeeRegistrationView.Count<EmployeeRegistrationView>() != 0 ? selEmployeeRegistrationView.Single() : null; 

        }

Here I like to use Generic to make single common function for data retrieval. I have implemented same thing in Nhibernate with generic so that I can use one method for retrieving all types of Domain object. The sample code is below.

NHibernate Code:

public T GetByCriteria(Dictionary<string, string> items)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                ICriteria cr = GetCriteria(session, items);

                T entity = cr.UniqueResult<T>();

                return entity;
            }
        }


protected ICriteria GetCriteria(ISession session, Dictionary<string, string> items)
        {
            ICriteria cr = session.CreateCriteria(typeof(T));

                foreach (string key in items.Keys)
                {
                    Type entityType = typeof(T);
                    System.Reflection.PropertyInfo criteriaProperty =
                        entityType.GetProperty(key);
                    cr.Add(Restrictions.Eq(key, Convert.ChangeType(items[key], criteriaProperty.PropertyType)));
                }

            return cr;
        }

Here the ICriteria interface does the wonder for adding a criteria to a object.
I am trying to achieve same thing in LINQ to SQL. It will save me a lot of code. Any idea how to achieve the same thing that I have achieved in NHibernate ? Thanks for help.