Browse Source

[WebApiUtils] Get object by primary key

feature/authentication-tests
Robin Thoni 9 years ago
parent
commit
b7338ce60c
1 changed files with 19 additions and 7 deletions
  1. 19
    7
      WebApiUtils/BusinessManager/SqlServerManager.cs

+ 19
- 7
WebApiUtils/BusinessManager/SqlServerManager.cs View File

@@ -192,6 +192,24 @@ namespace iiie.WebApiUtils.BusinessManager
192 192
             return Add(DboToDbStatic(obj));
193 193
         }
194 194
 
195
+        /// <summary>
196
+        /// Get an object by its primary key(s)
197
+        /// </summary>
198
+        /// <param name="pairs">The key names and values</param>
199
+        /// <returns>The object</returns>
200
+        public static OpResult<TDbObject> GetByPrimary(params KeyValuePair<string, object>[] pairs)
201
+        {
202
+            var param = Expression.Parameter(typeof(TDbObject), "x");
203
+            Expression totalExp = null;
204
+            foreach (var pair in pairs)
205
+            {
206
+                var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
207
+                totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
208
+            }
209
+            var lambda = Expression.Lambda<Func<TDbObject, bool>>(totalExp, param);
210
+            return GetSingle(lambda);
211
+        }
212
+
195 213
         /// <summary>
196 214
         /// Get an object by its id
197 215
         /// </summary>
@@ -199,13 +217,7 @@ namespace iiie.WebApiUtils.BusinessManager
199 217
         /// <returns>The object</returns>
200 218
         public static OpResult<TDbObject> GetById(long id)
201 219
         {
202
-            var param = Expression.Parameter(typeof(TDbObject), "x");
203
-            var exp = Expression.Lambda<Func<TDbObject, bool>>(
204
-                Expression.Equal(
205
-                    Expression.Property(param, "id"),
206
-                    Expression.Constant(id)
207
-                ), param);
208
-            return GetSingle(exp);
220
+            return GetByPrimary(new KeyValuePair<string, object>("id", id));
209 221
         }
210 222
 
211 223
         /// <summary>

Loading…
Cancel
Save