我们有下表
TABLE [dbo].[SoftwareItems](
[SoftwareItemId] [int] IDENTITY(1,1) NOT NULL,
[Type] [varchar](32) NOT NULL,
[SoftwareItem] [varchar](100) NOT NULL)
获取行的密钥(如果存在或插入新行并返回新行的密钥)的最有效方法是什么。以下是我到目前为止:
var ctx = new Entities();
var si = ctx.SoftwareItems.FirstOrDefault(s => s.SoftwareItem1.Equals(SoftwareItem) && string.Compare(s.Type, SoftwareItemType) == 0);
if (si != null)
return si.SoftwareItemId;
else
{
si = new SoftwareItem();
si.SoftwareItem1 = SoftwareItem;
si.Type = SoftwareItemType;
ctx.SoftwareItems.Add(si);
ctx.SaveChanges();
return si.SoftwareItemId;
}
答案 0 :(得分:0)
避免加载整个现有对象并仅加载密钥的轻微改进将是:
var ctx = new Entities();
int? softwareItemId = ctx.SoftwareItems
.Where(s => s.SoftwareItem1.Equals(SoftwareItem) &&
string.Compare(s.Type, SoftwareItemType) == 0)
.Select(s => (int?)s.SoftwareItemId)
.FirstOrDefault();
if (softwareItemId.HasValue)
return softwareItemId.Value;
else
{
// your original code...
}