我是实体框架的新手,尝试更新实体并返回它及其关系。首先,EF 不返回实体及其关系。它只返回自身,所以我决定首先更新实体,然后获取实体及其关系。但是这次当我调用
GetSingle
方法时,我得到了该实体 null。
这是实体类:
public class Seller : BaseEntity
{
public string UserId { get; set; } = String.Empty;
public ApplicationUser? User { get; set; }
public string? Speciality { get; set; } = String.Empty;
public string? Industry { get; set; } = String.Empty;
public string? Graduation { get; set; } = String.Empty;
public Guid? SellerImageId { get; set; }
public Image? SellerImage { get; set; }
public Guid? SellerMainCategoryId { get; set; }
public Category? SellerMainCategory { get; set; }
public string SellerBio { get; set; } = String.Empty;
[NotMapped]
public IFormFile? ImageFile { get; set; }
//Navigation
public SellerCompany? SellerCompany { get; set; }
public List<SellerBankInfo>? SellerBankInfos { get; set; }
}
这是控制器方法:
[HttpPut]
[Route("update")]
public async Task<ResponseData> Update([FromBody] UpdateSellerDto updateSellerDto)
{
var sellerEntity = _mapper.Map<Seller>(updateSellerDto);
sellerEntity = await _sellerService.UpdateSellerAsync(sellerEntity);
if (sellerEntity is null)
{
return Execute(UnSuccessRequest, () =>
{
return "Error on Update";
});
}
var updatedSeller = await _sellerService.GetSingleSeller(Guid.Parse(updateSellerDto.Id));
var sellerResponse = _mapper.Map<GetSingleSellerResponseDto>(updatedSeller);
return Execute(SuccessRequest, () =>
{
return sellerResponse;
});
}
这里是更新的服务方法(该方法更新但仅返回实体,而不返回具有“SellerMainCategory”等关系的实体):
public async Task<Seller> UpdateSellerAsync(Seller seller)
{
var updateResult = _context.Sellers.Update(seller);
await _context.SaveChangesAsync();
return updateResult.Entity;
}
这是服务中的单个 get 方法;当我只调用这个方法时,这有效,但当我在更新后调用它时返回 null:
public async Task<Seller?> GetSingleSeller(Guid userId)
{
var seller = await _context.Sellers
.Include(c => c.User)
.Include(x => x.SellerMainCategory)
.FirstOrDefaultAsync(s => s.UserId == userId.ToString());
return seller;
}
我就是无法理解EF的工作流程。
您应该在更新对象之前将实体状态设置为已修改(SaveChangesAsync)。