2014-02-11 80 views
1

我正在使用此代碼在ClientAccountAccess表中創建一條記錄。但是在任何時候只能有一個記錄在這張表中。所以如果這個函數被調用,我首先要檢查一個記錄是否存在,如果它刪除它然後添加新記錄。如果記錄存在刪除它?

 private static void SetAccessCode(string guidCode) 
     { 
      using (EPOSEntities db = new EPOSEntities()) 
      { 

//so here would I say something like (see below) 

       ClientAccountAccess client = new ClientAccountAccess(); 
       client.GUID = guidCode; 
       db.AddToClientAccountAccesses(client); 
       db.SaveChanges(); 
      } 
     } 

// 
ClientAccountAccess clientAccessCodes = db.ClientAccountAccesses 
        .OrderByDescending(x => x.Id) 
        .Take(1) 
        .Single(); 

       if clientAccessCodes.exists() 

        db.DeleteObject(clientAccessCodes); 
       db.SaveChanges(); 
+0

問題是什麼? (btw,小心:你已經創建了一個競賽條件) –

+1

你不能更新記錄嗎? –

+1

似乎這些事件需要作爲一個單一的工作單元來執行。如果是這樣的話,你應該在每件事物上包裝一個'TransactionScope'。 –

回答

1

嘗試這樣的事情...

bool doesItExistAlready = (from caa in db.ClientAccountAccesses 
          where css.id == guidCode 
          select caa).Any(); 

if (doesItExistAlready) 
{ 
    // Delete old record 
    db.DeleteObject(PUTIDENTIFIERHERE); 
} 

// Add new record 
ClientAccountAccess client = new ClientAccountAccess(); 
client.GUID = guidCode; 
db.AddToClientAccountAccesses(client); 
1

你真的需要將其刪除?如果你沒有,你可以這樣做:

private static void SetAccessCode(string guidCode) 
{ 
    using (EPOSEntities db = new EPOSEntities()) 
    { 
     var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode); 
     if(c!=null) 
      return; 
     var client = new ClientAccountAccess(){GUID=guidCode}; 
     db.AddToClientAccountAccesses(client); 
     db.SaveChanges(); 
    } 
} 

那麼你只會插入它,如果它不已經存在

如果您需要在創建對象之前將其刪除。你可以這樣做:

private static void SetAccessCode(string guidCode) 
{ 
    using (EPOSEntities db = new EPOSEntities()) 
    { 
     var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode); 
     if(c!=null) 
     { 
      db.ClientAccountAccesses.DeleteObject(c); 
      db.SaveChanges(); 
     } 
     var client = new ClientAccountAccess(){GUID=guidCode}; 
     db.AddToClientAccountAccesses(client); 
     db.SaveChanges(); 
    } 
} 

如果你可以更新你可以做這樣的事情的對象:

private static void SetAccessCode(string guidCode) 
{ 
    using (EPOSEntities db = new EPOSEntities()) 
    { 
     var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode); 
     if(c==null) 
     { 
      c=new ClientAccountAccess(); 
      db.AddToClientAccountAccesses(client); 
     } 
     c.GUID=guidCode; 
     db.SaveChanges(); 
    } 
}