如何仅更新插入的一行

时间:2015-09-25 12:54:08

标签: c# sql entity-framework asp.net-web-api

实体:

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

故事:

每个设备都有一系列功能。 但其中只有一个可能是主要的。

'IsPrimary'的价值可以改变:

  • 如果设备在db
  • 中没有任何主要功能,则WebAPI在创建后设置为“true”
  • 可以由用户manualy更改

有很多并行请求。当它们执行并且设备没有获得特征时,所有这些并行请求都会创建“IsPrimary”=真实特征。

如何处理这种情况?

2 个答案:

答案 0 :(得分:1)

我会稍微处理一下:IsPrimary应该是设备的属性,而不是功能。像这样:

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; }
}

此外,您应该实施一些并发检查:https://msdn.microsoft.com/en-ca/data/jj592904.aspx

因此,如果两个用户同时尝试修改同一个设备,其中一个会收到错误,他/她可以采取相应的行动。或者你可以处理并发问题但是你觉得合适。

这可能会有所帮助: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

答案 1 :(得分:0)

设置一个标志,在该标志中写入数据库中的记录,并检查表中是否存在已经具有IsPrimary = true的属性。这样,您的数据库中就不会有多个IsPrimary记录。然后,用户可以在现有记录之间切换主要功能。