【发布时间】:2011-12-22 03:42:12
【问题描述】:
上下文
对于使用 MVVM 模式的 WPF 应用程序,我使用实体上的 IDataErrorInfo 接口验证我的实体(/业务对象),以便 WPF 自动调用我的实体中的验证规则,并且验证错误自动出现在视图中。 (在本文中受到 Josh Smith 的启发:http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/
这适用于简单的验证规则,例如(名称 > 10 个字符,值必须 > 0)
但是当模型中的验证规则更复杂时该怎么办(例如名称必须是唯一的/属性的最大值在另一个实体中定义)。我首先想到通过让实体引用存储库来解决这个问题,但这感觉不好,因为我认为应该只有从存储库到实体的引用而不是其他方式(创建循环引用)
从 Recipe 实体引用 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 必须为
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();
}
【问题讨论】:
标签: wpf silverlight validation mvvm entity