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

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

问题描述

我有一个访问SQL和Windows Azure的MVC应用程序。逻辑流程是这样的:

 人物<  - >查看<  - > Controller.ConvertPersonH​​ere(X)下 - →; StorageContext.DoDataAction<  - > AzurePersonTableEntity

ConvertPersonH​​ere的答案是<一个href=\"http://stackoverflow.com/questions/5087183/does-using-implicit-explicit-conversion-operators-violate-single-responsibility\">this堆栈溢出问题以及它的模型实体转换为存储实体

 公共类Person
{
    公共字符串名称{;设置;}
    公众诠释ID {获取;设置;}
}公共类PersonEntity:TableServiceEntity
{
    公共字符串名称{;设置;}
    公众诠释ID {获取;设置;}    // code设置PartitionKey
    // code设置RowKey
}


  1. 现在,我加入WCF的组合,我应该如何去访问数据的功能呢?假设我现在在控制器中有 .Save(人)的方法和希望保存(人)我的WCF调用。


  2. 我需要抽象出在控制器中的数据的行为?



解决方案

我要重构code这样的 - 移动功能从人转换为PersonEntity,反之亦然到一个单独的映射,将节省的功能分离库以及和移动控制器的code来调用映射器和存储库,以单独的服务了。结果
因此,在您的控制器方法将类似于:

 公众的ActionResult的someMethod(人人)
{
    如果(ModelState.IsValid)
    {
        _personService.Save(人)
        返回视图(成功);
    }
    返回查看();
}

而在你的WCF服务,你就可以重新使用code。为了使用DataAnnotations属性,可以使用类似以下的方法来验证WCF类 - 的 http://blog.jorgef.net/2011/01/odata-dataannotations.html

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

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. 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.

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

解决方案

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();
}

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应用程序,它应该使用控制器访问数据库,以保持“干”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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