I am using .net core 7. I am sending a json as below. The json object I sent can always change. For example, when I don't submit the "Description" field, it changes to "null" in the database.
{
"id": 105,
"name": "Test1"
}
In the json object I sent, when there is no "description", it marks it as null and replaces it in the database.
Company
table:
public class Company
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
}
CompanyUpdateDTO
:
public class CompanyUpdateDto
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public DateTime? UpdatedDate { get; set; }
}
I am sending it as an entity through the controller:
[HttpPut]
public async Task<IActionResult> Update([FromBody] CompanyUpdateDto updateCompany)
{
await _service.UpdateAsync(_mapper.Map<Company>(updateCompany));
return CreateActionResult(CustomResponseDto<CompanyUpdateDto>.Success(204));
}
I want to remove columns with null
field in incoming json object. I did this as follows, but I could not convert it back to the entity structure. Can we remove the null
values in this field and convert them back to entity?
public async Task UpdateAsync(T entity)
{
//JsonSerializerOptions options = new()
//{
// DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
//};
//T serialized = (T)Convert.ChangeType(JsonSerializer.Serialize(entity, options), typeof(T));
//Console.WriteLine(serialized);
//var sonuc2 = (T)Convert.ChangeType(serialized, typeof(T));
_repository.Update(entity);
await _unitOfWork.CommitAsync();
}
CodePudding user response:
You can try to find the Company with id,and then replace the name of the Company,here is a demo of efcore:
var Company= await _context.Companys.FirstOrDefaultAsync(s => s.Id == updateCompany.Id);//you can get the company by id with your code
Company.Name=updateCompany.Name;
await _service.UpdateAsync(_mapper.Map<Company>(Company));
CodePudding user response:
You could try as below to Update part of the entity for simple types:
foreach (var prop in company.GetType().GetProperties())
{
if (prop.GetValue(company).ToString().Contains("Some") || prop.Name=="Id")
{
_context.Entry(company).Property(prop.Name).IsModified = false;
}
else{
_context.Entry(company).Property(prop.Name).IsModified = true;
}
}
try
{
await _context.SaveChangesAsync();
}
The result: