我有一个访问 SQL 和 Windows Azure 的 MVC 应用程序。逻辑流程如下所示:
Person <--> View <--> Controller.ConvertPersonHere(x) <--> StorageContext.DoDataAction <--> AzurePersonTableEntity
ConvertPerson这里是 this Stack Overflow question 的答案它将模型实体转换为存储实体
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
}
既然我要添加 WCF,我应该如何访问数据函数?假设我当前在 Controller 中有一个
.Save(Person)
方法,并且希望从我的 WCF 调用中Save(Person)
。我需要抽象出 Controller 中的数据操作吗?
最佳答案
我会像这样重构代码 - 将从 Person 转换为 PersonEntity 的功能移动到单独的映射器,反之亦然,将保存功能移动到单独的存储库,并将用于调用映射器和存储库的 Controller 代码也移动到单独的服务.
因此 Controller 中的方法将类似于:
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
关于wcf - 如果WCF在MVC应用程序中,它是否应该使用 Controller 访问数据库以保留 'DRY',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5092736/