Search code examples
loopsstored-proceduresentity-framework-4data-access-layer

Could not loop thru data return from DAL Entity framework in PL


I am using Entity Framework 4 in my project. One basic requirement is to fetch data from database using stored procedure and loop those data in presentation layer and also bind with dropdownlist, grid control etc.

I am following the flow as follow:

PL call BLL and BLL call DAL

Sample codes :

DAL:

namespace DAL.Repository
{
    public class CountryRepository
    {
        public static IList GetCountry(string CountryId)
        { 
            using(MyDBEntities context=new MyDBEntities())
            {
               // it calls SP in DB thru EF to fetch data
                return context.GetCountry(CountryId).ToList();

            }
        }
    }
}

BLL

namespace BLL
{
   public class Country
    {
       public static IList GetCountry(string CountryId)
       {
           return DAL.Repository.CountryRepository.GetCountry(CountryId);
       }
    }
}

PL

  ddlCountry.DataTextField = "CountryName";
  ddlCountry.DataValueField = "CountryId";
  ddlCountry.DataSource= BLL.Country.GetCountry(string.Empty);
  ddlCountry.DataBind();

* Here binding working fine. But i am not sure is it the best option. Please suggest me.

       System.Collections.IEnumerator lst= BLL.Country.GetCountry(string.Empty).GetEnumerator();
        while(lst.MoveNext())
        {
            string s = ((DAL.Entity.ORM.Country)(lst.Current)).Countryname;

         /* This is the main issue. To get data from [current]
         reference of [DAL.Entity.ORM.Country] is required.
         It is strongly not good practice to keep reference
         of DAL in PL. */
        }

What is best way of fetching data from database using EF with Stored procedure and using those data Independently in PL?

Is is safe to use static method as i have used?

Please suggest me.


Solution

    1. Ideally you don't want to reference your DAL in your PL. You could have a shared type with your PL and BL. The BL would convert your DAL type to this type before returning it.

    2. For the example you have show yes static method should be fine.