How come the "Table" classes Generated in the Dbml do not contain useful events like
OnBeforeInsert
OnBeforeUpdate
OnAfterInsert
etc.
Am I missing something?
This question is related to frustration trying to set timestamp columns.
UPDATE
I created the following method of doing this neatly what does everyone think?
public class Model
{
internal virtual void OnBeforeInsert()
{
}
internal virtual void OnBeforeUpdate()
{
}
}
public partial class DbDataContext
{
public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
foreach (var insert in this.GetChangeSet().Inserts)
{
if (insert is Model)
{
((Model)insert).OnBeforeInsert();
}
}
foreach (var update in this.GetChangeSet().Updates)
{
if (update is Model)
{
((Model)update).OnBeforeUpdate();
}
}
base.SubmitChanges(failureMode);
}
}
public partial class Address : Model
{
internal override void OnBeforeInsert()
{
var created = DateTime.Now;
this._Modified = created;
this._Created = created;
}
}
I had a similar issue like this recently.
There is a partial method in the generated class for "OnValidate". Simply declaring the method in your partial will force it to be called (vb.net does not support partial methods like c#) or in c# simply declare a partial method.
The method is passed a System.Data.Linq.ChangeAction enum that is either: Delete, Insert, Update, or None.
Below is a sample of what you did using the built in partial method.
public partial class Address
{
private partial void OnValidate(System.Data.Linq.ChangeAction action)
{
if (action == System.Data.Linq.ChangeAction.Insert)
{
var created = DateTime.Now;
this._Modified = created;
this._Created = created;
} else if (action == System.Data.Linq.ChangeAction.Update) {
this._Modified = DateTime.Now;
}
}
}
Related
I think I'm missing something fundamental when implementing a LinqToHql generator class.
I've successfully registered the SQL Server 2008 contains query using a custom dialect with this registration:
RegisterFunction("contains", new StandardSQLFunction("contains", null));
I have only one class with a full text index to be queried:
public class SearchName
{
public virtual Guid Id {get; set;}
public virtual string Name {get; set;} // this is the search field
}
The contains function works properly in HQL:
var names = Session.CreateQuery("from SearchName where contains(Name,:keywords)")
.SetString("keywords", "john")
.List();
and the generated SQL is perfect:
select searchname0_.Id as Id4_,
searchname0_.Name as Name4_
from Search_Name searchname0_
where contains(searchname0_.Name, 'john' /* #p0 */)
The next challenge was to implement the Linq to HQL generator:
public class MyLinqtoHqlGeneratorsRegistry :
DefaultLinqToHqlGeneratorsRegistry
{
public MyLinqtoHqlGeneratorsRegistry()
{
this.Merge(new ContainsGenerator());
}
}
public class ContainsGenerator : BaseHqlGeneratorForMethod
{
public ContainsGenerator()
{
SupportedMethods = new[] {
ReflectionHelper.GetMethodDefinition<SearchName>(d => d.Name.Contains(String.Empty))
};
}
public override HqlTreeNode BuildHql(MethodInfo method,
System.Linq.Expressions.Expression targetObject,
ReadOnlyCollection<System.Linq.Expressions.Expression> arguments,
HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
return treeBuilder.MethodCall("contains",
visitor.Visit(targetObject).AsExpression(),
visitor.Visit(arguments[0]).AsExpression()
);
}
}
}
Calling the method like this:
var namesLinq = Session.Query<SearchName>().Where(x=> x.Name.Contains("john")).ToList();
Unfortunately, this doesn't seem to override the built-in Contains method, and the generated SQL is wrong:
select searchname0_.Id as Id4_,
searchname0_.Name as Name4_
from Search_Name searchname0_
where searchname0_.Name like ('%' + 'john' /* #p0 */ + '%')
Is it not possible to override the default Contains method, or have I just made a silly mistake?
PS - I'm using NHibernate 3.3.1.4000
OK, I've finally figured it out!
First, I managed to delete the registration code from my configuration:
...
.ExposeConfiguration(cfg =>
{
cfg.LinqToHqlGeneratorsRegistry<MyLinqtoHqlGeneratorsRegistry>();
...
}
Second, don't try to override the existing Linq behaviors. I moved my Contains extension method to the full-text class.
Third, build the Hql tree correctly.
For others trying to implement a SQL 2008 Free-text contains search, here's the complete implementation:
public static class DialectExtensions
{
public static bool Contains(this SearchName sn, string searchString)
{
// this is just a placeholder for the method info.
// It does not otherwise matter.
return false;
}
}
public class MyLinqtoHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public MyLinqtoHqlGeneratorsRegistry()
: base()
{
RegisterGenerator(ReflectionHelper.GetMethod(() =>
DialectExtensions.Contains(null, null)),
new ContainsGenerator());
}
}
public class ContainsGenerator : BaseHqlGeneratorForMethod
{
string fullTextFieldName = "Name";
public ContainsGenerator()
: base()
{
SupportedMethods = new[] {
ReflectionHelper.GetMethodDefinition(() =>
DialectExtensions.Contains(null, null))
};
}
public override HqlTreeNode BuildHql(MethodInfo method,
System.Linq.Expressions.Expression targetObject,
ReadOnlyCollection<System.Linq.Expressions.Expression> arguments,
HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
// cannot figure out how to interrogate the model class to get an
// arbitrary field name...
// perhaps the RegisterGenerator() call above could be used to pass a
// property name to the ContainsGenerator constructor?
// in our case, we only have one full text searchable class, and its
// full-text searchable field is "Name"
HqlExpression[] args = new HqlExpression[2] {
treeBuilder.Ident(fullTextFieldName).AsExpression(),
visitor.Visit(arguments[1]).AsExpression()
};
return treeBuilder.BooleanMethodCall("contains", args);
}
}
For the above to work, you must have declared and used your custom dialect:
public class CustomMsSql2008Dialect : NHibernate.Dialect.MsSql2008Dialect
{
public CustomMsSql2008Dialect()
{
RegisterFunction(
"contains",
new StandardSQLFunction("contains", null)
);
}
}
Then you can use your new contains search this way:
var namesLinq = Session.Query<SearchName>().Where(x => x.Contains("john")).ToList();
... and the resulting SQL is perfect! (at least if you only have one table you're performing full-text searches on)
EDIT: UPDATED IMPLEMENTATION TO SUPPORT MORE THAN ONE FULLTEXT 'Contains' SEARCH PER QUERY.
Here's the revised version:
public static class DialectExtensions
{
public static bool FullTextContains(this string source, string pattern)
{
return false;
}
}
public class MyLinqtoHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public MyLinqtoHqlGeneratorsRegistry()
: base()
{
RegisterGenerator(ReflectionHelper.GetMethod(() => DialectExtensions.FullTextContains(null, null)),
new FullTextContainsGenerator());
}
}
public class FullTextContainsGenerator : BaseHqlGeneratorForMethod
{
public FullTextContainsGenerator()
{
SupportedMethods = new[] { ReflectionHelper.GetMethod(() => DialectExtensions.FullTextContains(null, null)) };
}
public override HqlTreeNode BuildHql(MethodInfo method,
System.Linq.Expressions.Expression targetObject,
ReadOnlyCollection<System.Linq.Expressions.Expression> arguments,
HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
HqlExpression[] args = new HqlExpression[2] {
visitor.Visit(arguments[0]).AsExpression(),
visitor.Visit(arguments[1]).AsExpression()
};
return treeBuilder.BooleanMethodCall("contains", args);
}
}
To use the revised version, the syntax is slightly different:
var namesLinq = Session.Query<SearchName>().Where(x => x.Name.FullTextContains("john")).ToList();
I have three MvxSpinners in my android view.
These spinners are binded to three different lists.
and Mode of data binding is TwoWay for these spinners.i.e. when this view is
displayed,all of these three spinners are get displayed with the predefined values.
When user change the value in first spinner,then second spinner will be clear and
get loaded with new values based on the selected value in first spinner.
How can I achieve this?
There's many ways to accomplish this, where the code placement is really up to you. Overall the idea would be to have a "SelectedItem" object that you can pass into your method and "Load" the next List.
Please keep in mind that this code is more traditional MVVM, but can easily be converted to MVVMCross equivalent. I believe all these types should be supported by MVVMCross.
private MyFirstObject _selectedFirstObject;
public MyFirstObject SelectedFirstObject
{
get { return _selectedFirstObject; }
set
{
_selectedFirstObject = value;
RaisePropertyChanged("SelectedFirstObject");
if(value != null)
LoadMySecondObjects(value);
}
}
private ObservableCollection<MyFirstObject> _myFirstObjects;
public ObservableCollection<MyFirstObject> MyFirstObjects
{
get { return _myFirstObjects; }
set
{
_myFirstObjects = value;
RaisePropertyChanged("MyFirstObjects");
}
}
private ObservableCollection<MySecondObject> _mySecondObjects;
public ObservableCollection<MySecondObject> MySecondObjects
{
get { return _mySecondObjects; }
set
{
_mySecondObjects = value;
RaisePropertyChanged("MySecondObjects");
}
}
public void LoadMySecondObjects(MyFirstObject current)
{
//Wherever you're pulling data from
MySecondObjects = MyDataService.GetAll(current);
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
I had the same problem but only if you add null value (as a default value) to your ItemsSource and try to reset SelectedItem to null. SelectedItem is changed in ViewModel but not in the spinner. In that case there's number of solutions but I used message to inform View to set selected item
public class SpinnerSelectionChanged : MvxMessage
{
public SpinnerSelectionChanged(object sender, string spinnerName, int position): base(sender)
{
SpinnerName = spinnerName;
Position = position;
}
public string SpinnerName { get; set; }
public int Position { get; set; }
}
in View
private void OnSpinnerSelectionChanged(SpinnerSelectionChanged obj)
{
switch (obj.SpinnerName)
{
case "City":
_spinnerCity.SetSelection(obj.Position);
break;
case "Office":
_spinnerOffice.SetSelection(obj.Position);
break;
}
}
In order to find walk-around for absence RelativeSource in MvvmCross, I used Stuart's suggestion and implemented WrappingList
MVVMCross changing ViewModel within a MvxBindableListView
However, I see this trace every bind it happens and I wonder, how worse it is:
Binding to IEnumerable rather than IList - this can be inefficient,
especially for large lists
Maybe there are any other suggestions?
public class WrappingCommandsList<T> : IList<WrappingCommandsList<T>.Wrapped>
{
private readonly List<T> _realList;
private readonly Action<T> _realActionOnClick;
public class Wrapped
{
public IMvxCommand ClickCommand { get; set; }
public T TheItem { get; set; }
}
public WrappingCommandsList(List<T> realList, Action<T> realActionOnClick)
{
_realList = realList;
_realActionOnClick = realActionOnClick;
}
private Wrapped Wrap(T item)
{
return new Wrapped()
{
ClickCommand = new MvxCommand(() => _realActionOnClick(item)),
TheItem = item
};
}
public WrappingCommandsList<T>.Wrapped this[int index]
{
get
{
return Wrap(_realList[index]);
}
set
{
throw new NotImplementedException();
}
}
public int Count
{
get { return _realList.Count; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<WrappingCommandsList<T>.Wrapped> GetEnumerator()
{
foreach (var item in _realList)
{
yield return Wrap(item);
}
}
How inefficient depends on the length of your list and how far down it the used has scrolled.
eg if the user is showing item 93,256 on the screen then the only way for the list adapter to find item 93,256 is to get the enumerator and to call MoveNext 93,256 times.
Whereas if your list only has 5 items the problem is bounded by 5.
For your particular WrappingCommandsList try implementing IList as well as IList<T> - the mvx code can't generate the IList<T> accessors at runtime because of xamarin.ios AoT compilation restrictions.
I have a partial class to extend one of my LinqToSql classes. In this partial class I have the following calculated field.
public bool IsInCluster
{
get
{
return Cluster != null;
}
}
In order for a grid column databound to this field to update automatically I have implemented the following partial method.
partial void OnClusterIDChanged()
{
SendPropertyChanged("IsInCluster");
}
However when I update the Cluster property as shown in the following code the OnClusterIDChanged method does not get called:
private void ExecCreateClusterCommand()
{
var cluster = new Cluster()
{
ID = Guid.NewGuid(),
MailService = AppState.CurrentMailService
};
App.DataContext.Clusters.InsertOnSubmit(cluster);
foreach (DeliveryPoint deliveryPoint in SelectedDeliveryPoints)
{
deliveryPoint.Cluster = cluster;
}
App.DataContext.SubmitChanges();
}
I have successfully used this technique with other non navigation properties related to calculated fields. Is there a way to make this work?
In your setter for Cluster, call OnClusterIDChanged, if the state has changed.
The only solution I could find for this was to create a public method in the DeliveryPoint class enabling me to call SendPropertyChanged for the required field (navigation property):
public void CallSendPropertyChanged(string propertyName)
{
SendPropertyChanged(propertyName);
}
Is it possible to extend LINQ-to-SQL entity-classes with constructor-methods and in the same go; make that entity-class inherit from it's data-context class?--In essence converting the entity-class into a business object.
This is the pattern I am currently using:
namespace Xxx
{
public class User : Xxx.DataContext
{
public enum SiteAccessRights
{
NotRegistered = 0,
Registered = 1,
Administrator = 3
}
private Xxx.Entities.User _user;
public Int32 ID
{
get
{
return this._user.UsersID;
}
}
public Xxx.User.SiteAccessRights AccessRights
{
get
{
return (Xxx.User.SiteAccessRights)this._user.UsersAccessRights;
}
set
{
this._user.UsersAccessRights = (Int32)value;
}
}
public String Alias
{
get
{
return this._user.UsersAlias;
}
set
{
this._user.UsersAlias = value;
}
}
public User(Int32 userID)
{
var user = (from u in base.Users
where u.UsersID == userID
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User();
base.Users.InsertOnSubmit(this._user);
}
}
public User(Xxx.User.SiteAccessRights accessRights, String alias)
{
var user = (from u in base.Users
where u.UsersAccessRights == (Int32)accessRights && u.UsersAlias == alias
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User
{
UsersAccessRights = (Int32)accessRights,
UsersAlias = alias
};
base.Users.InsertOnSubmit(this._user);
}
}
public void DeleteOnSubmit()
{
base.Users.DeleteOnSubmit(this._user);
}
}
}
Update:
Notice that I have two constructor-methods in my User class. I'd like to transfer those to the User entity-class and extend the User entity-class on it's data-context class, so that the data-context is available to the entity-class on "new-up".
Hope this makes sense.
Rick Strahl has a number of really good articles that address what I think you are looking for. Check out his list of Linq Articles Here
Inheriting an entity from a data context is a bad idea. They are two discrete objects and are designed to operate that way. Doing this will cause all sorts of issues least of all problems with trying to submit a bunch of related changes together at the same time - going through multiple data contexts will cause this to fail as each tries to work independently.
It doesn't seem to make sense to make an entity a type of DataContext. It doesn't need to be a DataContext in order to be considered a business object, nor do you necessarily need to create a type that contains the original entity. It might be better to just extend the entity class and contain a reference to a DataContext using composition:
namespace Xxx.Entities
{
public partial class User : IDisposable
{ DataContext ctx;
public static GetUserByID(int userID)
{ var ctx = new DataContext();
var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);
if (user == null)
{
user = new User();
ctx.Users.InsertOnSubmit(user);
}
user.ctx = ctx;
return user;
}
public void Dispose() { if (ctx != null) ctx.Dispose(); }
}
}
If you just want the property names to be different than the database column names, do that in the mapping file.