使用存储库模式验证ASP.Net MVC 3中的实体框架实体的最佳做法? [英] Best practise for validating Entity Framework entities in ASP.Net MVC 3 using a repository pattern?

查看:81
本文介绍了使用存储库模式验证ASP.Net MVC 3中的实体框架实体的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发现几次,当我们向一些实体添加新的属性时,尽管我们保持最新的验证逻辑(现在只是一个服务类),但是我们错过了更新逻辑,在服务类中,我们从存储库中检索绑定,并将repo中的实体的所有属性设置为模型,然后尝试并保存。效果是新的字段永远不会被保存,因为我们忘记在更新逻辑中进行赋值。

I have found on a couple of occasions when we add new properties to some of the entities then although we keep up to date on the validation logic (which is just in a service class for now) but we miss the part in the update logic where in the service class we retrieve the bind from the repository and set all the properties of the entity in the repo to the model and then try and save. The effect is that the new field never gets saved because we forgot to do the assignment in the update logic.

控制器类有一个很好的UpdateModel(model)方法,它将为您做这一切,并确保它获得所有的属性。这样做很棒,但是它并没有解决额外的验证问题,而且服务从repo获取了实体。

The controller class has a nice UpdateModel(model) method which will do it all for you and make sure that it gets all the properties. This works great but it doesn't get around the problem of extra validation and the fact that the service gets the entity from the repo.

想要使用UpdateModel方法的场景,想做验证,并试图坚持使用存储库模式。我有意无视服务类,因为我不介意放弃它。

What is the best practise in the scenario where you want to use the UpdateModel method, want to do validation and are trying to stick the to repository pattern. I have purposefully left out the service class because I don't mind ditching it. It seems to be way to much hassle for what it is worth.

推荐答案

您可以实现 IValidatableObject 接口。

EF 4.1和MVC 3都知道这个接口。

Both EF 4.1 and MVC 3 are aware of this interface.

MVC将调用在UpdateModel方法中验证 moethod,如果有任何验证错误,它将抛出异常。 MVC甚至会将视图中的验证错误。 MVC验证

MVC will call the Validate moethod in the UpdateModel method and if there are any validation errors it will throw an exception. MVC will even put the validation error on the view. MVC Validation

EF将会在保存插入和更新之前调用此方法。

EF will also call this method before insertions and updations are saved.

您可以将所有验证方法

这篇关于使用存储库模式验证ASP.Net MVC 3中的实体框架实体的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆