Entity Framework Accessing Data

This post is more for myself, so I can go back here and check out how to write codes to query against an Entity Framework.

.NET Framework 4 , and future versions, will be focusing more on Entity SQL more than LINQ. Here’s a sample of how you can select 1 or more records given a condition.

1. Built the Entity instance

SignUpEntities _db = new SignUpEntities();

2. Create an Object Query 

ObjectQuery<orderhist> query = new ObjectQuery<orderhist>(“SELECT * FROM orderhist WHERE orderid = @orderid “, _db);

*note, this uses System.Data.Objects class

3. add paramters to the query

query.Parameters.Add(new ObjectParameter(“orderid”, _orderid));

4. Create a list and run, to allow code to iterate over the records

List<orderhist> _orderhist = query.ToList();

Sample full code

//* Get Order hist (checkorder) given orderid
        public static List<orderhist> GetOrderHistory(string _orderid)
        {
            try
            {
                //* use model
                SignUpEntitiesConnectionString _db = new SignUpEntitiesConnectionString();

               

                ObjectQuery<orderhist> query = new ObjectQuery<orderhist>(“SELECT * FROM orderhist WHERE orderid = @orderid “, _db);

                query.Parameters.Add(new ObjectParameter(“orderid”, _orderid));

                //* get the record
                List<orderhist> _orderhist = query.ToList();

                return _orderhist;
               
              
            }
            catch (Exception ex)
            {
                List<orderhist> _orderhist2 = new List<orderhist>();

                return _orderhist2;
              
            }

          

        }
    }


  1. sonborj posted this
My name is Sanborj.
and this is my life.