gpt4 book ai didi

c# - 找不到类型或命名空间(但应该是!)

转载 作者:行者123 更新时间:2023-12-04 17:02:40 26 4
gpt4 key购买 nike

我想通过使用命名空间而不是添加 Dto 来区分我的 DTO 和我的模型实体。后缀。所以,而不是有 CustomerCustomerDto , 有 CustomerDTO.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项目同时引用了 DALDTO项目。 API项目同时引用了 DLLDTO项目。

为什么我不能使用 DTO.Customer在我的 API Controller 中的使用方式与我在 CustomerService 中使用它的方式完全相同类(class)?

最佳答案

您可以为其中一个命名空间使用命名空间别名,以避免完全限定其中一个:

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 来救援

我建议你快速浏览一下 automapper ,这是将 dto 转换为类似对象的绝佳工具。

那能帮到你吗?

关于c# - 找不到类型或命名空间(但应该是!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com