C# 更新模型的属性 foreach(PropertyInfo prop在mine.GetType().GetProperties()中) { //如果它们不为null,则更新数据库模型上的属性 如果(属性GetValue(我的)!=null) { 矿井更新 .GetType() .GetProperty(属性名称) .SetValue(mineToUpdate,prop.GetValue(mine)); } } wait_context.SaveChangesAsync(); 返回mineToUpdate; }

C# 更新模型的属性 foreach(PropertyInfo prop在mine.GetType().GetProperties()中) { //如果它们不为null,则更新数据库模型上的属性 如果(属性GetValue(我的)!=null) { 矿井更新 .GetType() .GetProperty(属性名称) .SetValue(mineToUpdate,prop.GetValue(mine)); } } wait_context.SaveChangesAsync(); 返回mineToUpdate; },c#,json,asp.net-mvc,rest,asp.net-web-api2,C#,Json,Asp.net Mvc,Rest,Asp.net Web Api2,使用此方法,您可以更改模型,而无需担心更新逻辑,只要从更新DTO到数据库模型的映射是正确的。如果出于某种原因,您不打算使用JsonPatchDocument,并且您的客户机希望发送一个只指定几个属性的直接API调用,正如您在示例中所做的那样-查看patcharp库,这可以为您提供一个方向,或者一旦发布,您可以将其用作NuGet软件包。由于IETF建议使用这种格式的误导性暗示,因此被否决。您链接到的“此处”站点在查看了IETF的“关于”和“联系我们”页面后,似乎与IETF没有任何关联。@jramm

使用此方法,您可以更改模型,而无需担心更新逻辑,只要从更新DTO到数据库模型的映射是正确的。

如果出于某种原因,您不打算使用
JsonPatchDocument
,并且您的客户机希望发送一个只指定几个属性的直接API调用,正如您在示例中所做的那样-查看
patcharp
库,这可以为您提供一个方向,或者一旦发布,您可以将其用作NuGet软件包。由于IETF建议使用这种格式的误导性暗示,因此被否决。您链接到的“此处”站点在查看了IETF的“关于”和“联系我们”页面后,似乎与IETF没有任何关联。@jramm-同意否决票;我也有同样的反应。尽管做了一些进一步的研究,IETF实际上有一个单独的RFC,它描述的格式与Tipx给出的链接RFC6902中的格式相同。6902是5987的一个子集,因此使用它不是强制性的,甚至可能不是推荐的。Tipx可能会相应地更新你的答案?不,我会保持原样。我给出的示例正是您链接的RFC中“文档结构”部分的示例。虽然这不是一个100%完整的答案,但我坚持我的原始想法,即这是一个很好的信息,可以引导正确的方向。我的回答背后的主要思想是“小心,补丁不仅仅是SQL升级”。如果你想编辑答案,我猜!如果您试图将db模型上的值设置回null,该怎么办?@jimebe我想这是该方法的一个限制。也许您可以有一个要更新的属性列表,如果该属性包含在该列表中,则会更新,否则不会更新。这样,您就可以使用任何想要的属性值,包括null,并且只要它包含在列表中,它就会作为更新应用。
public class Member
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Created { get; set; }
    public DateTime BirthDate { get; set; }
    public bool IsDeleted { get; set; }
}
[Route("{id}")]
[HttpPut]
public async System.Threading.Tasks.Task<HttpResponseMessage> UpdateRow(int id, 
    [FromBody]Models.Member model)
{
    // Do some error checking
    // ...
    // ...

    var myDatabaseEntity = new BusinessLayer.Member(id);
    myDatabaseEntity.FirstName = model.FirstName;
    myDatabaseEntity.LastName = model.LastName;
    myDatabaseEntity.Created = model.Created;
    myDatabaseEntity.BirthDate = model.BirthDate;
    myDatabaseEntity.IsDeleted = model.IsDeleted;

    await myDatabaseEntity.SaveAsync();
}
{
    firstName: "Sara",
    lastName: "Smith",
    created: '2018/05/10",
    birthDate: '1977/09/12",
    isDeleted: false
}
{
    lastName: "Jones"
}
[Route("{id}")]
[HttpPatch]
public async System.Threading.Tasks.Task<HttpResponseMessage> UpdateRow(int id, 
    [FromBody]Models.Member model)
{
}
[
    { "op": "test", "path": "/a/b/c", "value": "foo" },
    { "op": "remove", "path": "/a/b/c" },
    { "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
    { "op": "replace", "path": "/a/b/c", "value": 42 },
    { "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
    { "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody]JsonPatchDocument<Node> value)
{
    try
    {
        //nodes collection is an in memory list of nodes for this example
        var result = nodes.FirstOrDefault(n => n.Id == id);
        if (result == null)
        {
            return BadRequest();
        }    
        value.ApplyTo(result, ModelState);//result gets the values from the patch request
        return NoContent();
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, ex);
    }
}
[DataContract(Name ="Node")]
public class Node
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "node_id")]
    public int Node_id { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "full_name")]
    public string Full_name { get; set; }
}
[
  { "op": "replace", "path": "full_name", "value": "NewNameWithPatch"},
  { "op": "replace", "path": "node_id", "value": 10}
]
[
  { "op": "test", "path": "property_name", "value": "value" },
  { "op": "remove", "path": "property_name" },
  { "op": "add", "path": "property_name", "value": [ "value1", "value2" ] },
  { "op": "replace", "path": "property_name", "value": 12 },
  { "op": "move", "from": "property_name", "path": "other_property_name" },
  { "op": "copy", "from": "property_name", "path": "other_property_name" }
]
public static StringContent ToPatchJsonContent(this object node, Encoding enc = null)
{
    List<PatchObject> patchObjectsCollection = new List<PatchObject>();

    foreach (var prop in node.GetType().GetProperties())
    {
        var patch = new PatchObject{ Op = "replace", Path = prop.Name , Value = prop.GetValue(node) };
        patchObjectsCollection.Add(patch);                
    }

    MemoryStream payloadStream = new MemoryStream();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(patchObjectsCollection.GetType());
    serializer.WriteObject(payloadStream, patchObjectsCollection);
    Encoding encoding = enc ?? Encoding.UTF8;
    var content = new StringContent(Encoding.UTF8.GetString(payloadStream.ToArray()), encoding, "application/json");

    return content;
}
[DataContract(Name = "PatchObject")]
class PatchObject
{
    [DataMember(Name = "op")]
    public string Op { get; set; }
    [DataMember(Name = "path")]
    public string Path { get; set; }
    [DataMember(Name = "value")]
    public object Value { get; set; }
}
    var nodeToPatch = new { Name = "TestPatch", Private = true };//You can use anonymous type
    HttpContent content = nodeToPatch.ToPatchJsonContent();//Invoke the extension method to serialize the object

    HttpClient httpClient = new HttpClient();
    string endPoint = "https://localhost:44320/api/nodes/1";
    var response = httpClient.PatchAsync(endPoint, content).Result;
public class UpdateModel
{
    public double? Temperature { get; set; }

    public int? Stock { get; set; }

    public string Name { get; set; }
}
public async Task<DbModel> Update(DbModel updateModel)
{
    // Find the existing model from the database
    var objToUpdate = await _context.Objects.FindAsync(updateModel.Id);
    if (mineToUpdate == null)
    {
        return null;
    }
    // Loop through all properties of the update model
    foreach (PropertyInfo prop in mine.GetType().GetProperties())
    {
        // If they are not null, update the property on the database model
        if (prop.GetValue(mine) != null)
        {
            mineToUpdate
                .GetType()
                .GetProperty(prop.Name)
                .SetValue(mineToUpdate, prop.GetValue(mine));
        }
    }
    await _context.SaveChangesAsync();
    return mineToUpdate;
}