2009-02-06 65 views
2

我正在尝试在MVC场景中进行验证。我有我的应用程序设置,以便它具有使用Linq2SQL的数据/存储库层,并在我的域模型中创建对象。然而,我不直接将我的Linq2SQL对象暴露给我的应用程序的其余部分,现在,我的域模型大多看起来像我的数据库表。我想这样做是为了以后我想放弃Linq2SQL。在MVC中验证模型的一部分

然后我有一个服务层从我的控制器调用来执行操作并从我的数据层获取我的域模型。

我想使用验证框架,如xVal。你的模型应该包含你的验证规则似乎是普遍的看法。我的问题是你如何验证部分模型(或各种状态)?例如,我有一个拥有用户名,密码和其他属性的用户对象。我有一个登录操作,我想确保提供用户名和密码。但是,当我创建一个新用户时,我想要更多的字段。当我已经有我的用户对象时,在模型中创建一个Login对象似乎很奇怪。

现在,我的登录操作只是发送一个用户名和密码参数。

回答

2

你说得对,模型图层中的验证通常是正确的。问题可能出现在你的域模型中---你有一个用户的想法,直到它拥有所有的东西才有效。

想一想用户可以是匿名用户,或者可以填写用户。想一想的一个简单方法是让用户拥有一个Credentials对象的实例;这也是一个很好的地方来跟踪权限等。

+0

这是一个有趣的方式来看看它。基本上,它会告诉我在哪里需要将我的物理模型的某些部分转换为更多逻辑模型。这将使验证零件更容易。我会看看这是怎么回事。谢谢! – Jonathan 2009-02-06 22:37:51

+0

是的。要做的事情是考虑DOMAIN模型。在这里你可以在你的“故事”中看到你的会话可以匿名的情况;对象模型应该表示这一点。另一个版本会有一个会话 - 一个可以匿名的用户。 – 2009-02-06 22:48:17

0

对不起,但我想不出超出你的榜样。用户对象不应该有登录方法。我做的是有以下几种

public class User 
{ 
    public bool ConfirmPassword(string password) 
    { 
    ... 
    } 
} 

然后一个存储库。这通过他们的userName找到用户,然后检查ConfirmPassword以查看它是否正确,如果不正确则返回null。

public interface IUserRepository 
{ 
    ..other stuff.. 
    User GetByUserNameAndPassword(string userName, string password); 
} 

至于验证,我通常有2种获取约束的方法。

//The constraint itself 
public interface IConstraint 
{ 
    string Name { get; } 
    bool IsValid(); 
} 

//A way to get constraints that are inexpensive to evaluate, such 
//as Name != null etc. This can be implemented as a service to provide 
//custom constraints from an external source (such as rows in a DB) 
//which then additionally checks "instance" if it implements the 
//interface and adds its constraints to the result too. 

//These are the kinds of constraints I evaluated in the GUI every 
//time the object changes, so I can show a list of errors. 
public interface IConstraintProvider 
{ 
    IEnumerable<IConstraint> GetConstraints(object instance); 
} 

//Finally a way to get constraints that are expensive to evaluate, this 
//includes checking invariants that might involve DB access. These constraints 
//(along with the cheap evaluation constraints) are all evaluated before 
//my persistence service attempts to write the object's changes to the DB 
public interface IPreSaveConstraintProvider 
{ 
    IEnumerable<IConstraint> GetConstraints(object instance); 
}