我们目前正在为每个数据表构建一个具有基本CRUD功能的web api和控制器 . 我们遇到的问题是更新 . 我们创建了自定义绑定模型以仅引入我们需要的数据,然后将该绑定模型转换为对象,并将其传递给我们的更新函数 .
我们遇到的问题是,当客户端通过POST发送数据时,我们的绑定模型接收它并填充它们使用值设置的字段,以及填充为null的所有其他内容 . 因此,当我们将其转换为数据对象并将其发送到Update函数时,它会将未从客户端设置的字段覆盖为null .
这显然会引起问题,因为我们不希望用户意外删除信息 .
以下是我们如何使用客户端,绑定模型和更新来运行的示例,
The Team Binding Model
/// <summary>A Binding Model representing the essential elements of the Team table</summary>
public class TeamBindingModel
{
/// <summary>The Id of the team</summary>
[Required(ErrorMessage = "An ID is required")]
public int ID { get; set; }
/// <summary>The name of the team</summary>
[Required(ErrorMessage = "A Team Name is required")]
[Display(Name = "Team Name")]
[StringLength(35)]
public string Team1 { get; set; }
/// <summary>The email associated with the team</summary>
[StringLength(120)]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public bool ShowDDL { get; set; }
}
The UpdateTeam CRUD Method
// PUT: api/Team
/// <summary>
/// Attempt to update a team with a given existing ID
/// </summary>
/// <param name="team">TeamBindingModel - The binding model which needs an Id and a Team name</param>
/// <returns>IHttpActionResult that formats as an HttpResponseCode string</returns>
[HttpPut]
[Authorize(Roles = "SystemAdmin.Teams.Update")]
public async Task<IHttpActionResult> UpdateTeam(TeamBindingModel team)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
// Convert the binding model to the Data object
Team teamObject = team.ToObject();
unitOfWork.TeamRepository.Update(teamObject);
await unitOfWork.Save();
}
catch (DbUpdateConcurrencyException)
{
return BadRequest();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
The ToObject Function
/// <summary>Takes the Team Binding model and converts it to a Team object</summary>
/// <returns>Team Object</returns>
public virtual Team ToObject()
{
// Setup the data object
Team newObject = new Team();
// Instantiate the basic property fields
newObject.ID = this.ID;
newObject.Team1 = this.Team1;
newObject.Email = this.Email;
newObject.ShowDDL = this.ShowDDL;
return newObject;
}
The Update Function
public virtual void Update(TEntity entityToUpdate)
{
try
{
dbSet.Attach(entityToUpdate);
dbContext.Entry(entityToUpdate).State = EntityState.Modified;
}
catch (Exception ex)
{
throw ex;
}
}
The Save Function
public async Task Save()
{
await dbContext.SaveChangesAsync();
}
Client calls / Testing / Error
// Add team to update and remove
var db = new genericDatabase();
var teamDB = new Team { Team1 = "testTeam", Email = "test@email.com", ShowDDL = true};
db.Teams.Add(teamDB);
db.SaveChanges();
// Look for items in the database
var originalTeamInQuestion = (from b in db.Teams
where b.Team1 == "testTeam"
select b).FirstOrDefault();
// Create Team object with the some changes
var team = new
{
ID = originalTeamInQuestion.ID,
Team1 = "changedTestTeam",
ShowDDL = false,
};
// This is the API call which sends a PUT with only the parameters from team
var teamToUpdate = team.PutToJObject(baseUrl + apiCall, userAccount.token);
// Look for items in the database
var changedTeamInQuestion = (from b in db.Teams
where b.Team1 == "changedTestTeam"
select b).FirstOrDefault();
// This Assert succeeds and shows that changes have taken place
Assert.AreEqual(team.Team1, changedTeamInQuestion.Team1);
// This Assert is failing since no Email information is being sent
// and the binding model assigns it to Null since it didn't get that
// as part of the PUT and overrides the object on update.
Assert.AreEqual(originalTeamInQuestion.Email, changedTeamInQuestion.Email);
关于某些替代方法的任何想法?我们曾想过要求客户端首先通过对API进行GET调用然后更改对象来获取整个对象,但如果客户端不遵循该协议,则会非常危险地消除敏感数据 .
1 回答
我已经实现了一个静态类,它将获取enity对象并仅更新实体的脏属性 . 这允许最终用户在需要时将值显式设置为null .