如果 WCF 在 MVC 应用程序中,它是否应该使用控制器访问数据库以保持“DRY" [英] If WCF is in a MVC application, should it use the controller to access the database to keep 'DRY'

查看:26
本文介绍了如果 WCF 在 MVC 应用程序中,它是否应该使用控制器访问数据库以保持“DRY"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个访问 SQL 和 Windows Azure 的 MVC 应用程序.逻辑流程如下所示:

I have an MVC application that accesses SQL and Windows Azure. The logical flow looks like this:

Person <--> View <--> Controller.ConvertPersonHere(x) <--> StorageContext.DoDataAction <--> AzurePersonTableEntity

ConvertPersonH​​ere 是这个堆栈溢出问题的答案 并将模型实体转换为存储实体

ConvertPersonHere is the answer to this Stack Overflow question and it converts the Model entity to the Storage entity

public class Person
{
    public string Name {get;set;}
    public int ID {get;set;}
}

public class PersonEntity : TableServiceEntity
{
    public string Name {get;set;}
    public int ID {get;set;}

    // Code to set PartitionKey
    // Code to set RowKey
}

  1. 既然我将 WCF 添加到组合中,我应该如何访问数据函数?假设我目前在控制器中有一个 .Save(Person) 方法,并且想要从我的 WCF 调用中Save(Person).

  1. Now that I'm adding WCF to the mix, how should I go about accessing data functions? Assume I have currently have a method to .Save(Person) in the controller and want to Save(Person) from my WCF call.

我需要抽象出控制器中的数据操作吗?

Do I need to abstract out the data actions in the controller?

推荐答案

我会像这样重构代码 - 将从 Person 转换为 PersonEntity 的功能(反之亦然)移动到单独的映射器,将保存功能也移动到单独的存储库, 并将用于调用映射器和存储库的控制器代码也移动到单独的服务中.
因此,您的控制器中的方法将类似于:

I would refactor the code like this - move the functionality to convert from Person to PersonEntity and vice versa to a separate mapper, move saving functionality to separate repository as well, and move controller's code for invoking mapper and repository to separate service too.
So methods in your controller will look similar to:

public ActionResult SomeMethod(Person person)
{
    if (ModelState.IsValid)
    {
        _personService.Save(person)
        return View("Success");
    }
    return View();
}

并且在您的 WCF 服务中,您将能够重用代码.为了使用 DataAnnotations 属性验证 WCF 中的类,您可以使用类似于以下的方法 - http://blog.jorgef.net/2011/01/odata-dataannotations.html

And in your WCF service you'll be able to reuse the code. In order to validate the classes in WCF using DataAnnotations attributes, you can use the approach similar to the following - http://blog.jorgef.net/2011/01/odata-dataannotations.html

这篇关于如果 WCF 在 MVC 应用程序中,它是否应该使用控制器访问数据库以保持“DRY"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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