简体   繁体   中英

How to update only one row from inserted

The entity:

  public class Feature { 
     public int Id {get;set;}
     public int DeviceId {get;set;}
     public string Value {get;set;}
     public bool IsPrimary {get;set;}
   }

The story:

Each device has a list of features. But only one of them could be primary.

Value of 'IsPrimary' could be changed:

  • WebAPI sets to 'true' after creation if device has not got any primary feature in db
  • Could be changed by user manualy

There are a lot of parallel requests. And when they executes and device hasn't got featues all these parallel requests creates 'IsPrimary'=true feature.

How do handle this situation?

I would handle it a bit differently: the IsPrimary should be a property of the device, not the Feature. Something like this:

public class Device
{
    public List<Feature> Features { get; set; }
    public Feature PrimaryFeature { get; set; }
    // ...
}

public class Feature 
{ 
    public int Id { get; set; }
    public int DeviceId { get; set; }
    public string Value { get; set; }
}

Also you should implement some concurrency checks: https://msdn.microsoft.com/en-ca/data/jj592904.aspx

So if two users try to modify the same Device at the same time, one of them will get an error, and he/she can act accordingly. Or you can handle the concurrency issue however you feel appropriate.

This might be a bit more helpful: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

Set a flag where you write the record in the database and check if there is a property in the table that already has IsPrimary = true. This way you won't have multiple IsPrimary records in your database. And then the user can switch the primary feature between the existing records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM