public class VillageDto
{
public int id { get; set; }
public string Name { get; set; }
public string HindiName { get; set; }
public int CentreId { get; set; }
}
public class CentreDto
{
public int id { get; set; }
public string Name { get; set; }
public string HindiName { get; set; }
}
public class BankDto
{
public int id { get; set; }
public string BankName { get; set; }
public String BankShortName { get; set; }
}
public class GrowerDto
{
public int Id { get; set; }
public int VillageId { get; set; }
public VillageDto village { get; set; }
public string Name { get; set; }
public string FatherName { get; set; }
public string HindiName { get; set; }
public string HindiFatherName { get; set; }
public string AccountNo { get; set; }
public int CentreId { get; set; }
public CentreDto centre { get; set; }
public int BankId { get; set; }
public BankDto bank { get; set; }
}
public MappingProfile()
{
Mapper.CreateMap<Village, VillageDto>();
Mapper.CreateMap<VillageDto, Village>();
Mapper.CreateMap<Grower, GrowerDto>();
Mapper.CreateMap<GrowerDto, Grower>();
Mapper.CreateMap<Bank, BankDto>();
Mapper.CreateMap<BankDto, Bank>();
}
public class GrowerController : ApiController
{
private ApplicationDbContext _context;
public GrowerController()
{
_context = new ApplicationDbContext();
}
public IHttpActionResult GetAllGrowers(int? pagenumber, int? pagesize)
{
var allgrowers = _context.growers.Include(v => v.village).ToList().Select(Mapper.Map<Grower, GrowerDto>).OrderBy(g => g.Id);
var currentPageNumber = pagenumber ?? 1;
var currentPageSize = pagesize ?? 5;
return Ok(allgrowers.Skip((currentPageNumber - 1) * currentPageSize).Take(currentPageSize));
}
}
返回结果
1。种植者的主键为(id,villageid)
2。Villageid也是村庄模型
3的外键和主键。当调用API时,API会多次返回相同的数据。
首先,不要这样做:
var allgrowers = _context.growers.Include(v => v.village).ToList().Select(Mapper.Map<Grower, GrowerDto>).OrderBy(g => g.Id);
相反,使用Automapper的ProjectTo
方法来处理IQueryable
。上面的代码将选择ALL数据,并在分页之前将所有内容映射到dto。你想保持IQuertable
正确到最后,以确保它建立一个查询,只是返回所需的数据页。
接下来,我将避免在构造函数中为DbContext初始化模块级变量。您希望确保在控制器完成时处置DbContext。通常,当您使用依赖注入时,您将通过构造函数传入DbContext实例。既然你还没有这样做,我将删除:
public GrowerController()
{
_context = new ApplicationDbContext();
}
并在需要的地方将ApplicationDbContext作用在using
块中。
// For example purposes, you need to manage the mapper configurations rather
// than rely on the static Mapper API.
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Village, VillageDto>();
cfg.CreateMap<Grower, GrowerDto>();
cfg.CreateMap<Bank, BankDto>();
});
using (var context = new ApplicationDbContext())
{
var query = _context.growers
.OrderBy(g => g.Id)
.ProjectTo<GrowerDto>(config);
var currentPageNumber = pagenumber ?? 1;
var currentPageSize = pagesize ?? 5;
var results = query
.Skip((currentPageNumber - 1) * currentPageSize)
.Take(currentPageSize)
.ToList();
return Ok(results);
}
您可以使用断点检查results
值,以查看您是否获得了期望的数据。如果您看到重复,那么我会考虑对数据库运行一个分析器,以查看正在生成哪些SQL,您可以手动运行该分析器以检查结果。我一时还不知道到底是什么原因会导致同样的记录重复出现。这可能与您的实体映射或特定的模式状态有关。(颗)