對於使用MVVM模式驗證我的實體(/業務對象)一個WPF應用程序實體,以便我的實體中的驗證規則由WPF自動調用,驗證錯誤自動顯示在視圖中。 (由約什 - 史密斯這篇文章的啓發:http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/
這適用於像(名> 10個字符簡單的驗證規則確定,值必須是> 0)
但要做到什麼時候在模型驗證規則更復雜的(像名稱必須是唯一的/最大值的屬性是在另一個實體中定義的)我首先想到通過讓實體具有對存儲庫的引用來解決這個問題,但是這並不好,因爲我認爲應該只能從存儲庫中引用到實體,而不是其他方式(創建循環引用)
是否從Re中引用了「合法」 cipe實體添加到ConfigurationRepository中。或者你有更好的建議? 如果在驗證依賴於其他實體/服務的情況下如何實現實體/業務對象驗證,您是否有建議?
下面是我真實世界問題的簡化代碼。 在配方實體中,我想驗證最高溫度是否低於存儲在Configuration.MaximumTemperature中的值。 你會如何解決這個問題?
的配置實體(商店的最大容許溫度爲配方)
public class Configuration: INotifyPropertyChanged, IDataErrorInfo
{
private int _MaxTemperatureSetpoint;
public int MaxTemperatureSetpoint
{
get { return _MaxTemperatureSetpoint; }
set
{
if (value != _MaxTemperatureSetpoint)
{
_Setpoint = value;
RaisePropertyChanged("MaxTemperatureSetpoint");
}
}
}
簡化配方(類,其中用戶配置與所希望的溫度(TemperatureSetpoint配方)和期望時間(TimeMilliSeconds)。TemperatureSetpoint必須爲< Configuration.MaxTemperature)
public class Recipe: INotifyPropertyChanged, IDataErrorInfo
{
private int _TemperatureSetpoint;
public int TemperatureSetpoint
{
get { return _TemperatureSetpoint; }
set
{
if (value != _TemperatureSetpoint)
{
_Setpoint = value;
RaisePropertyChanged("Setpoint");
}
}
}
private int _TimeMilliSeconds;
public int TimeMilliSeconds
{
get { return _TimeMilliSeconds; }
set
{
if (value != _TimeMilliSeconds)
{
_TimeMilliSeconds= value;
RaisePropertyChanged("TimeMilliSeconds");
}
}
}
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string propertyName]
{
get
{
switch(propertyName)
{
case "TimeMilliSeconds":
//TimeMilliSeconds must be < 30 seconds
if (TimeMilliSeconds < 30000)
{ return "TimeMilliSeconds must be > 0 milliseconds";}
case "TemperatureSetpoint":
//MaxTemperatureSetpoint < maxTemperature stored in the ConfigurationRepository
int maxTemperatureSetpoint = ConfigurationRepository.GetConfiguration().MaxTemperatureSetpoint;
if (TemperatureSetpoint> maxTemperatureSetpoint)
{ return "TemperatureSetpoint must be < " + maxTemperatureSetpoint.ToString();}
}
}
#endregion
}
配方庫
public interface IRecipeRepository
{
/// <summary>
/// Returns the Recipe with the specified key(s) or <code>null</code> when not found
/// </summary>
/// <param name="recipeId"></param>
/// <returns></returns>
TemperatureRecipe Get(int recipeId);
.. Create + Update + Delete methods
}
配置庫
public interface IConfigurationRepository
{
void Configuration GetConfiguration();
}
感謝您的回答!我喜歡將業務規則注入模型的想法,因爲這會將模型的依賴關係移除到存儲庫。 我看到的唯一缺點是模型驗證現在分散在代碼中(在簡單屬性模型中,在ViewModel中進行驗證,依賴於其他服務),而不是在1個地方(模型) –
@ArjendenHartog You也可以在創建對象的任何層中添加驗證。例如,您可以有一個「CustomerRepository」查詢數據庫,創建模型,添加驗證,然後將對象返回給調用它的人。 – Rachel