Dynamic LINQ query to get Field value from Database

前端 未结 4 1278
耶瑟儿~
耶瑟儿~ 2021-01-18 03:20

is it possible?

Public String Get_Filed_By_Id(string table_Name,String Field_Name,string PK_val)
{
    string strRes=\"\";
    using(mydbcontext db=new mydbc         


        
4条回答
  •  耶瑟儿~
    2021-01-18 04:08

    I had this question too ,I know this is not exactly what you want and you need write more code but it's much cleaner than those you want to write.
    Using repository pattern
    For every table you should have a model class and Repository class.
    Consider this code(this code from one of my project)
    This is my comment table(this can be anything with or without navigation property)

      public sealed class Comment
    {
        public string CommentText { get; set; }
        public DateTime PostDate { get; set; }
        public int PostId { get; set; }
        public int? PageId { get; set; }
        public Page Page { get; set; }
        public User User { get; set; }
        public string UserId { get; set; }
        public int? ParentId { get; set; }
        public Comment[] ChildComments { get; set; }
    }  
    

    RepositoryComment

      public sealed class CommentRepository : BaseRepository
    {
        public CommentRepository(BabySitterContext context)
            : base(context)
        {
        }
    }  
    

    and a base class that you send your query with table name(here model) and field(you can extend clas for more functionality)

    public class BaseRepository where T : class
    {
        protected BabySitterContext Context;
        private readonly PluralizationService _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));
        public BaseRepository(BabySitterContext context)
        {
            this.Context = context;
        }
        public bool Add(T t)
        {
            Context.Set().Add(t);
            Context.SaveChanges();
            return true;
        }
        public bool Update(T t)
        {
            var entityName = GetEntityName();
    
            object originalItem;
            var key = ((IObjectContextAdapter)Context).ObjectContext.CreateEntityKey(entityName, t);
            if (((IObjectContextAdapter)Context).ObjectContext.TryGetObjectByKey(key, out originalItem))
            {
                ((IObjectContextAdapter)Context).ObjectContext.ApplyCurrentValues(key.EntitySetName, t);
            }
            Context.SaveChanges();
            return true;
        }
        public void Attach(T t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
    
            Context.Set().Attach(t);
            Context.SaveChanges();
        }
        public void Remove(T t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
            Context.Set().Remove(t);
            Context.SaveChanges();
        }
        public IEnumerable Get(Expression> filter = null, Func, IOrderedQueryable> orderBy = null, string includeProperties = "")
        {
            IQueryable query = Context.Set();
    
            if (filter != null)
            {
                query = query.Where(filter.Expand());
            }
    
            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }
    
            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }
        private string GetEntityName() where TEntity : class
        {
            return string.Format("{0}.{1}", ((IObjectContextAdapter)Context).ObjectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name));
    
        }
    
        public virtual IEnumerable GetByBusinessKey(T entity)
        {
            return null;
        }
    }    
    

    For any other table just make model class and reposiotry then inherite from base class

    Using code

     var context = new BabySitterContext();
     var  _commentRepository = new CommentRepository(context);
     var comment = _commentRepository.Get(x => x.PostId == id).FirstOrDefault();
    

提交回复
热议问题