虽然不是专家,但我必须创建一个解决方案,其中我的主要对象有一个值列表。让我们称之为对象 A 有一个在数据库中映射的 ApplicationValues 列表。ApplicationValues 有一个键(表单字段,例如电话号码)和值。
由于 ApplicationValues 是一个 EntitySet,我必须创建 get 和 set 方法来正确处理设置特定 ApplicationValue。我的数据库中还有一个 ApplicationRules 列表,它定义了这些应用程序值可以采用的内容。
这是一段代码,可以帮助您开发满足您需求的解决方案。
public partial ApplicationValue
{
public string Key;
public string Value;
}
public partial ApplicationRule
{
public string ValidationFormat;
public string ValidationError;
public bool Required;
}
public partial class A
{
public void SetValue(string key, string value)
{
//ApplicationValues is the list of values associated to object A
ApplicationValue v = ApplicationValues.SingleOrDefault
(k => k.Key == key);
//if we already have this value
if (v != null)
{ //...then we can simply set and return
v.Value = value;
return;
}
//else we need to create a new ApplicationValue
v = new ApplicationValue
{
AffinityID = this.ID,
Key = key,
Value = value
};
ApplicationValues.Add(v);
}
public string GetValue(ApplicationField key)
{
return GetValue(key, String.Empty);
}
public string GetValue(ApplicationField key, string defaultValue)
{
if (ApplicationValues == null)
return defaultValue;
ApplicationValue value = ApplicationValues.SingleOrDefault
(f => f.Key == key.ToString());
return (value != null) ? value.Value : defaultValue;
}
然后为了进行表单验证,我循环通过 ApplicationRules(它定义是否需要一个字段,包含一个正则表达式等)并将其与 FormCollection 匹配。
public ActionResult Details(FormCollection form)
{
IList<ApplicationRule> applicationRules = //get my rules from the DB
if (!(ValidateApplication(applicationRules, form, a)))
{
ModelState.AddModelError("message", "Please review the errors below.");
return View(a);
}
...
}
private bool ValidateApplication(IList<ApplicationRule> applicationRules,
FormCollection form, A a)
{
//loop through the application rules
foreach (ApplicationRule ar in applicationRules)
{
//try and retrieve the specific form field value using the key
string value = form[ar.Key];
if (value == null)
continue;
//set the model value just in case there is an error
//so we can show error messages on our form
ModelState.SetModelValue(ar.Key, ValueProvider[ar.Key]);
//if this rule is required
if (ar.Required)
{ //...then check if the field has a value
if (String.IsNullOrEmpty(value))
{
ModelState.AddModelError(ar.Key, "Field is required");
continue;
}
}
//if this rule has a validation format
if (!String.IsNullOrEmpty(ar.ValidationFormat))
{ //...then check the value is of the correct format
Regex re = new Regex(ar.ValidationFormat);
if (!re.IsMatch(value))
{
ModelState.AddModelError(ar.Key, ar.ValidationError);
continue;
}
}
a.SetValue(ar.Key, value);
}
return ModelState.IsValid;
}