private static Expression<Func<TEntity,bool>> HasSameIdAsCurrentBindingSourceObject<TEntity,TId>(Expression<Func<TEntity,TId>> idPropertySelector, TEntity currentObject)
where TEntity: class
{
if(idPropertySelector==null)throw new ArgumentNullException("idPropertySelector");
Func<TEntity,TId> getIdentityProperty = idPropertySelector.Compile();
TId currentId = getIdentityProperty(currentObject);
ConstantExpression currentIdConstant = Expression.Constant(currentId,typeof(TEntity));
ParameterExpression parameter = idPropertySelector.Parameters[0];
Expression theArgumentId = idPropertySelector.Body;
return Expression.Lambda<Func<TEntity,bool>>(Expression.Equal(theArgumentId,currentIdConstant),parameter);
}
private EventHandler CreateGenericBindingSourceChangedEventHandler<TEntity,TId>(Expression<Func<TEntity,TId>> idPropertySelector, Func<DataContext> openDataContext, TextBox textBox)
where TEntity: class
{
if(idPropertySelector==null)throw new ArgumentNullException("idPropertySelector");
if(openDataContext==null)throw new ArgumentNullException("openDataContext");
if(textBox == null)throw new ArgumentNullException("textbox");
return (sender,e) => {
var bindingSource = sender as BindingSource;
if(sender==null)throw new InvalidOperationException();
var currentBindingSourceObject = bindingSource.Current as TEntity;
if(currentBindingSourceObject == null) throw new InvalidOperationException();
using(var cont = openDataContext())
{
Table<TEntity> table = cont.GetTable<TEntity>();
var theObjectHasTheSameIdAsTheCurrentBindingSourceObject = HasSameIdAsCurrentBindingSourceObject(idPropertySelector,currentBindingSourceObject);
var count = table.Count(theObjectHasTheSameIdAsTheCurrentBindingSourceObject);
if(count>0)
{
textBox.Enabled = false;
}
else
{
textBox.Enabled = true;
}
}
};
}
private void tuserBindingSource_CurrentChanged(object sender, EventArgs e)
{
return
CreateGenericBindingSourceChangedEventHandler <database.tuser,int>
( x => x.userid==cuser.userid,
() => new database.dbDataContext(context.Connection),
userIdTextBox
)(sender,e);
}