Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- partial class AcessaBanco
- {
- public IEnumerable<T> GetByPrimaryKeys<T>(params object[] IDs) where T : class
- {
- var mapping = this.Mapping.GetTable(typeof(T));
- var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
- 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));
- var param = Expression.Parameter(typeof(T), "e");
- List<T> l = new List<T>();
- foreach (var ID in IDs)
- {
- var predicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(Convert.ChangeType(ID, pkfield.Type))), param);
- var obj = this.GetTable<T>().SingleOrDefault(predicate);
- if (obj != null) l.Add(obj);
- }
- return l.AsEnumerable();
- }
- public T GetByPrimaryKey<T>(object ID, bool CreateIfNotExists = false) where T : class
- {
- bool isnew = false;
- return this.GetByPrimaryKey<T>(ID, CreateIfNotExists, ref isnew);
- }
- public T GetByPrimaryKey<T>(object ID, bool CreateIfNotExists, ref bool IsNew) where T : class
- {
- T obj = null;
- IsNew = false;
- try { obj = this.GetByPrimaryKeys<T>(new[] { ID }).SingleOrDefault(); } catch { }
- if (obj == null && CreateIfNotExists)
- {
- IsNew = true;
- obj = Activator.CreateInstance<T>();
- this.GetTable<T>().InsertOnSubmit(obj);
- }
- return obj;
- }
- }
Add Comment
Please, Sign In to add comment