kaizonaro

GetByPrimaryKey for LINQ

May 8th, 2020
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. partial class AcessaBanco
  2.     {
  3.         public IEnumerable<T> GetByPrimaryKeys<T>(params object[] IDs) where T : class
  4.         {
  5.             var mapping = this.Mapping.GetTable(typeof(T));
  6.             var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
  7.             if (pkfield == null) throw new Exception(string.Format("Table {0} does not contain a Primary Key field or is a composite primary key", mapping.TableName));
  8.             var param = Expression.Parameter(typeof(T), "e");
  9.             List<T> l = new List<T>();
  10.             foreach (var ID in IDs)
  11.             {
  12.                 var predicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(Convert.ChangeType(ID, pkfield.Type))), param);
  13.                 var obj = this.GetTable<T>().SingleOrDefault(predicate);
  14.                 if (obj != null) l.Add(obj);
  15.             }
  16.             return l.AsEnumerable();
  17.         }
  18.  
  19.         public T GetByPrimaryKey<T>(object ID, bool CreateIfNotExists = false) where T : class
  20.         {
  21.             bool isnew = false;
  22.             return this.GetByPrimaryKey<T>(ID, CreateIfNotExists, ref isnew);
  23.         }
  24.  
  25.         public T GetByPrimaryKey<T>(object ID, bool CreateIfNotExists, ref bool IsNew) where T : class
  26.         {
  27.             T obj = null;
  28.             IsNew = false;
  29.             try { obj = this.GetByPrimaryKeys<T>(new[] { ID }).SingleOrDefault(); } catch { }
  30.             if (obj == null && CreateIfNotExists)
  31.             {
  32.                 IsNew = true;
  33.                 obj = Activator.CreateInstance<T>();
  34.                 this.GetTable<T>().InsertOnSubmit(obj);
  35.             }
  36.             return obj;
  37.         }
  38.     }
Add Comment
Please, Sign In to add comment