Entity Framework的简单使用


        Model First 先有数据库在创建代码

         

一:新建一个winform项目为MyEF

            

二:右键项目添加实体数据模型

           

  选择从数据库生成

  然后勾选需要的数据库对象确定即可

  

   然后就可以看到EF自动生成的代码

   

   需要看详细信息可以

    

三:使用EF做简单的增删改查

   

   如果遇到这种错误是因为ef在生成的时候,两个地方都生成了

   

   把Designer.cs下边的JSDEntities删除就可以了

   删除不了文件就在代码中删除文件会自己删除


 1"简单的增删改查

更新使用的是不需查询的更新

 JSDEntities edm = new JSDEntities();

            //select
            var temp = from p in edm.accounts_top_up
                       where p.ID == 18410
                       select p;
            accounts_top_up atu = temp.Single();

            //update
            accounts_top_up at = new accounts_top_up() { USER_ID = 18412, ID = 18412 };
            DbEntityEntry<accounts_top_up> entry = edm.Entry<accounts_top_up>(at);
            entry.State = System.Data.EntityState.Unchanged;  
            entry.Property("USER_ID").IsModified = true;
            edm.SaveChanges();

            //add
            accounts_top_up a = new accounts_top_up() { USER_ID = 18412, ID = 18412 };
            edm.accounts_top_up.Add(a);
            edm.SaveChanges();

            //delete
            edm.Entry<accounts_top_up>(new accounts_top_up() {  ID = 18411}).State = EntityState.Deleted
            edm.SaveChanges();


如果有时候删除或更新的时候条件比如复杂,可以考虑先查询出来,在进行删除更新等操作



2:模糊查询

actualContext.PU.Where(a=>a.ErrorReason.Contains("sdfsdf"))使用Contains关键字


3:
   var list = from entity in actualContext.PSI
                               where (string.IsNullOrEmpty(entity.QYPortEN) || entity.QYPortEN == priceinfo.QYPortEN)
                               select entity;


4:where if

 where ((sortBy == "Buy equipment") ? entity.Type == "Sell" : true) &&
                               ((sortBy == "Sell equipment") ? entity.Type == "Buy" : true)


四:使用Entity Framework CodeFirst模式创建新数据库    先有代码在创建数据库

http://www.cnblogs.com/snowdream/archive/2011/01/22/entity-framework-feature-codefirst-create-database-and-model.html



五:enfity framework 动态条件


我们可以看到ef where里边传的类型就可以提出来先组织好参数


 NPDPriceDBEntities nde = new NPDPriceDBEntities();



            Expression<Func<Price_Info, bool>> fliter = a => (string.IsNullOrEmpty(_params.QYPortEN) || a.QYPortEN == _params.QYPortEN)
                && (string.IsNullOrEmpty(_params.ShipEn) || a.ShipEN == _params.ShipEn);

            if (_params.voyagemin != null && _params.voyagemin!=0)
            {
               fliter=  fliter.And(a => a.Voyage>=_params.voyagemin);
            }
            if (_params.voyagemax != null && _params.voyagemax != 0)
            {
               fliter =  fliter.And(a => a.Voyage <= _params.voyagemax);
            }

            List<Price_Info> plisyt = nde.Price_Info.Where(fliter).Take(9).ToList();
            return plisyt;

扩展方法

   public static class ExpressionBuilder
    {
        /// <summary>
        /// Compose two expression and merge all in a new expression
        /// </summary>
        /// <typeparam name="T">Type of params in expression</typeparam>
        /// <param name="first">Expression instance</param>
        /// <param name="second">Expression to merge</param>
        /// <param name="merge">Function to merge</param>
        /// <returns>New merged expressions</returns>
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // build parameter map (from parameters of second to parameters of first)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
            
            // replace parameters in the second lambda expression with parameters from the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            // apply composition of lambda expression bodies to parameters from the first expression 
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }
        /// <summary>
        /// And operator
        /// </summary>
        /// <typeparam name="T">Type of params in expression</typeparam>
        /// <param name="first">Right Expression in AND operation</param>
        /// <param name="second">Left Expression in And operation</param>
        /// <returns>New AND expression</returns>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And); 
        }
        /// <summary>
        /// Or operator
        /// </summary>
        /// <typeparam name="T">Type of param in expression</typeparam>
        /// <param name="first">Right expression in OR operation</param>
        /// <param name="second">Left expression in OR operation</param>
        /// <returns>New Or expressions</returns>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }

    }

 public sealed class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;

        /// <summary>
        /// Default construcotr
        /// </summary>
        /// <param name="map">Map specification</param>
        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        /// <summary>
        /// Replate parameters in expression with a Map information
        /// </summary>
        /// <param name="map">Map information</param>
        /// <param name="exp">Expression to replace parameters</param>
        /// <returns>Expression with parameters replaced</returns>
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        /// <summary>
        /// Visit pattern method
        /// </summary>
        /// <param name="p">A Parameter expression</param>
        /// <returns>New visited expression</returns>
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }

            return base.VisitParameter(p);
        }

    }

使用and,与or


http://www.devba.com/index.php/archives/811.html

http://vtocode.com/blog/index.php/2014/12/03/ef6-multi-condition-dynamic-query/


分组与函数





  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值