Click here to Skip to main content
15,919,358 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hellow everyone,

I was working on mvc3 and Entity Framework 4+. I have two class named Repository.cs and BaseClass.cs on the model side. Why and How I was using them. Once I imported these classes, then I create a class for any table and the class takes properties by inheritance from these classes.

BaseClass.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;

namespace Panelium.Models
{
    public class BaseMethod<TEntity> where TEntity : class
    {
        public Repository N2model = new Repository();
        public bool Insert(TEntity entity)
        {
            return N2model.Add(entity);
        }
        public void InsertorUpdate(TEntity entity, int Id)
        {
            if (Id > 0)
            {
                N2model.Update(entity);
            }
            else
            {
                N2model.Add(entity);
            }
        }
        public bool Update(TEntity entity)
        {
            return N2model.Update(entity);
        }
        public bool Update(TEntity entity, params string[] kismialanlar)
        {
            return N2model.Attach(entity, kismialanlar);
        }
        public bool Delete(int Id)
        {
            return N2model.Delete<TEntity>(Id);
        }
        public bool Delete(int[] Idler)
        {
            try
            {
                for (int i = 0; i < Idler.Length; i++)
                {
                    N2model.Delete<TEntity>(Idler[i]);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public TEntity Select(int Id)
        {
            var sc = N2model.GetByKey<TEntity>(Id);
            if (sc == null)
            {
                return (TEntity)Activator.CreateInstance(typeof(TEntity));
            }
            return sc;
        }
        public IEnumerable<TEntity> SelectAll()
        {
            return N2model.GetAll<TEntity>();
        }
        public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> criteria)
        {
            return N2model.Find<TEntity>(criteria);
        }
    }
}


Repository.cs


XML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data;
using System.Linq.Expressions;
using System.Data.SqlClient;
using System.Data.Metadata.Edm;
using System.Reflection;

namespace Panelium.Models
{
    public class Repository
    {
        private Object _objectContext;

        public Repository()
        {
           _objectContext = new PaneliumEntities();
        }


        public int TableType { get; set; }

        public TEntity GetByKey<TEntity>(object keyValue) where TEntity : class
        {
            EntityKey key = GetEntityKey<TEntity>(keyValue);

            object originalItem;
            if (ObjectContext.TryGetObjectByKey(key, out originalItem))
            {
                return (TEntity)originalItem;
            }
            return default(TEntity);
        }

        public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
        {
            var entityName = GetEntityName<TEntity>();
            var q = ObjectContext.CreateQuery<TEntity>(entityName);
            //return ObjectContext.CreateQuery<TEntity>(entityName);
            return q;
        }

        public IQueryable<TEntity> GetQuery<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            return GetQuery<TEntity>().Where(predicate);
        }

        public IEnumerable<TEntity> Get<TEntity>(Expression<Func<TEntity, string>> orderBy, int pageIndex, int pageSize, SortOrder sortOrder = SortOrder.Ascending) where TEntity : class
        {
            if (sortOrder == SortOrder.Ascending)
            {
                return GetQuery<TEntity>().OrderBy(orderBy).Skip(pageIndex).Take(pageSize).AsEnumerable();
            }
            return GetQuery<TEntity>().OrderByDescending(orderBy).Skip(pageIndex).Take(pageSize).AsEnumerable();
        }

        public IEnumerable<TEntity> Get<TEntity>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, string>> orderBy, int pageIndex, int pageSize, SortOrder sortOrder = SortOrder.Ascending) where TEntity : class
        {
            if (sortOrder == SortOrder.Ascending)
            {
                return GetQuery<TEntity>().Where(predicate).OrderBy(orderBy).Skip(pageIndex).Take(pageSize).AsEnumerable();
            }
            return GetQuery<TEntity>().Where(predicate).OrderByDescending(orderBy).Skip(pageIndex).Take(pageSize).AsEnumerable();
        }


        public TEntity First<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            return GetQuery<TEntity>().FirstOrDefault(predicate);
        }

        public bool Add<TEntity>(TEntity entity) where TEntity : class
        {
            if (entity == null)
            {
                return false;
            }
            else
            {
                try
                {
                    ObjectContext.AddObject(GetEntityName<TEntity>(), entity);
                    SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

        }

        public bool Attach<TEntity>(TEntity entity, params string[] alanlar) where TEntity : class
        {
            if (entity == null)
            {
                return false;
            }
            else
            {
                try
                {
                    ObjectContext.AttachTo(GetEntityName<TEntity>(), entity);
                    ObjectStateEntry entry = ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
                    foreach (var item in alanlar)
                    {
                        entry.SetModifiedProperty(item);
                    }
                    SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public void SaveChanges()
        {
            this.ObjectContext.SaveChanges();
        }

        public bool Delete<TEntity>(TEntity entity) where TEntity : class
        {
            if (entity == null)
            {
                return false;
            }
            else
            {
                try
                {
                    ObjectContext.DeleteObject(entity);
                    SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

        }

        public bool Delete<TEntity>(Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            TEntity records = First<TEntity>(criteria);
            return Delete<TEntity>(records);

        }

        public bool Delete<TEntity>(int Id) where TEntity : class
        {
            TEntity records = GetByKey<TEntity>(Id);
            return Delete<TEntity>(records);

        }

        public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
        {
            return GetQuery<TEntity>().AsEnumerable();
        }

        public bool Update<TEntity>(TEntity entity) where TEntity : class
        {
            try
            {
                var fqen = GetEntityName<TEntity>();

                object originalItem;
                EntityKey key = ObjectContext.CreateEntityKey(fqen, entity);
                if (ObjectContext.TryGetObjectByKey(key, out originalItem))
                {
                    ObjectContext.ApplyCurrentValues(key.EntitySetName, entity);
                    SaveChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public IEnumerable<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return GetQuery<TEntity>().Where(criteria);
        }

        public int Count<TEntity>() where TEntity : class
        {
            return GetQuery<TEntity>().Count();
        }

        public int Count<TEntity>(Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return GetQuery<TEntity>().Count(criteria);
        }

        private ObjectContext ObjectContext
        {
            get
            {
                return this._objectContext;
            }
        }

        private string GetEntityName<TEntity>() where TEntity : class
        {
            if (TableType == 0)
            {
                // normal tablolar için
                string entitySetName = _objectContext.MetadataWorkspace
                    .GetEntityContainer(_objectContext.DefaultContainerName, DataSpace.CSpace)
                    .BaseEntitySets.Where(bes => bes.ElementType.Name == typeof(TEntity).Name).First().Name;
                return string.Format("{0}.{1}", _objectContext.DefaultContainerName, entitySetName);
            }
            else
            {
                // store procedureler için
                string entitySetName = _objectContext.MetadataWorkspace
                    .GetEntityContainer(_objectContext.DefaultContainerName, DataSpace.CSpace)
                    .FunctionImports.Where(bes => bes.Name == typeof(TEntity).Name).First().Name;
                return string.Format("{0}.{1}", _objectContext.DefaultContainerName, entitySetName);
            }
        }

        private EntityKey GetEntityKey<TEntity>(object keyValue) where TEntity : class
        {
            var entitySetName = GetEntityName<TEntity>();
            var objectSet = ObjectContext.CreateObjectSet<TEntity>();
            var keyPropertyName = objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
            var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });
            return entityKey;
        }
    }
}


Then I create a table named Users in Db. However in model I dont type any code.
I just creare a class named Users in model and add
public class Users: BaseClasss<users> this.

Then I go to controller and I can use MEthods for any table.

The problem starts here. I Updated from VS10 to VS12. Therefore, now I am using MVC4 and Entity Framework 5.

So, my repository.cs does not work. Is there any repository class for EF5 ?

Thanks.
Emre.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900