如果需要从自定义模型活页夹中检索对象,则该活页夹是否应与服务层,存储库层或...交互? [英] If I need to retrieve an object from a custom model binder should the binder interact with the service layer, the repository layer, or ...?

查看:99
本文介绍了如果需要从自定义模型活页夹中检索对象,则该活页夹是否应与服务层,存储库层或...交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个与此类似的课程:

If I have a class similar to this:

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public Pet myPet { get; set; }
}

当我创建自定义模型活页夹时,表单中的Post将不会发送给Pet,它将发送如下数据:firstName:"myFirstName" lastName:"myLastName" myPet:"myPetsName"

When I create a custom model binder, the Post from my form will not be sending in a Pet, it would send in data like this: firstName: "myFirstName" lastName: "myLastName" myPet: "myPetsName"

由于传入了Pet的名称,而不是实际的Pet对象,因此需要从模型绑定程序中检索Pet对象.

Since the Pet's name is passed in, and not the actual Pet object, the Pet object needs to be retrieved from within the model binder.

我的问题是,模型绑定器应该与服务层,存储库层进行交互,还是应该与Pet进行交互?服务层的问题在于,初始化服务时,我似乎无法访问ModelState:(((this.ModelState)给我一个错误)

My question is, should the model binder be interacting with the Service Layer, the Repository Layer, or should it even be retrieving the Pet? The problem with the Service Layer is that I don't seem to have access to ModelState when initializing the service: ((this.ModelState) gives me an error)

_petService = new PetService(new ModelStateWrapper(this.ModelState));

如果我需要模型绑定器来创建Person对象,则需要以某种方式分配Pet ...我应该怎么做?

If I need the model binder to create a Person object, then the Pet would need to be assigned somehow... how am I supposed to do this?

推荐答案

我要做的是使用视图/表示模型而不是绑定到业务对象.请记住,您的用户可能输入了无效值,并且在提示他们纠正错误时,您将需要向用户重新显示这些无效值.但是您的真实"业务对象可能不会接受无效值.因此,视图模型必须允许任何用户输入,即使输入业务对象也不会接受.

What I do is use a view/presentation model instead of binding to business objects. Remember that your users might enter invalid values, and you will need to re-display these invalid values to the user when prompting them to correct their mistakes. But your "real" business objects probably won't accept invalid values. So the view model must allow for any user input, even input the business objects won't accept.

这使绑定变得容易.您仅需在使用(有效)用户输入来更新业务对象时,才需要绑定存储库.

This makes the binding easy. You don't need to hit a repository to bind, only when updating the business object with (valid) user input.

这篇关于如果需要从自定义模型活页夹中检索对象,则该活页夹是否应与服务层,存储库层或...交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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