我想通过使用命名空间而不是添加Dto
后缀来区分我的DTO与模型实体。因此,Customer
和CustomerDto
取代Customer
和DTO.Customer
。
这是我的代码,非常自我解释。
namespace MyCompany.DAL
{
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
using MyCompany.DAL;
namespace MyCompany.BLL
{
public class CustomerService : EntityService<Customer>, ICustomerService
{
IContext _context;
public CustomerService(IContext context) : base(context)
{
_context = context;
_dbset = _context.Set<Customer>();
}
// I can use DTO.Customer here without an issue,
// and Intellisense knows it's a namespace
public DTO.Customer GetById(int Id)
{
return _dbset.FirstOrDefault(x => x.Id == Id);
}
}
}
namespace MyCompany.DTO
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
}
using MyCompany.BLL;
namespace MyCompany.API.Controllers
{
public class CustomerController : ApiController
{
ICustomerService customerService;
public CustomerController(ICustomerService customerService)
{
this.customerService = customerService;
}
// GET: api/Customer/5
// [ResponseType(typeof(DTO.Customer))]
// Can't compile, 'The type or namespace name 'DTO' could not be found'
[ResponseType(typeof(MyCompany.DTO.Customer))] // This works
public IHttpActionResult Get(int id)
{
var customer = customerService.GetById(id);
return Ok(customer);
}
}
}
BLL
项目引用了DAL
和DTO
个项目。
API
项目引用了DLL
和DTO
个项目。
为什么我在API控制器中使用DTO.Customer
的方式与我在CustomerService
课程中使用它的方式完全相同?
答案 0 :(得分:1)
您可以使用其中一个命名空间的命名空间别名来避免完全限定其中一个:
using Co = MyCompany.Dto;
然后,您可以在代码中执行以下操作:
var customerA = new Customer(); // from your most used namespace
var customerB = new Co.Customer(); // from your least used namespace
这些仍然是不同的命名空间,而不是您指出的同一个对象。他们没有,也不应该互相转换。 DTO的全部意义在于避免腐败:)
自动救援
我建议您快速查看automapper,这是将dto转换为类似对象的绝佳工具。
这会帮助你吗?
答案 1 :(得分:0)
你可以试试这个:
using MyCompany.BLL;
using MyCompany; //<--- Add this
namespace MyCompany.API.Controllers
{
public class CustomerController : ApiController
{
...
}
}