2013-02-14 60 views
0

我創建了一個簡單的Windows控制檯應用程序來使用VS2012和.NET 4.5測試實體框架。如何使用EF刪除實例?

我添加了一個ADO.NET實體數據模型來從我的數據庫創建一個模型。我用這個語法來使用它,但我怎樣才能刪除一些東西?

static void Main(string[] args) 
    { 
     using (var ctx = new HKDBEntities()) 
     { 
      int wordId=2; 
      var selectedWords = (from o in context.Addresses 
           where o.word== wordId 
           select o).FirstOrDefault(); 

      //these syntaxt is unavailable why???? 
      ctx.Words.Delete(word); 
      ctx.DeleteObject(word); 

      // i test remove method but works not gave me some error 
      context.Words.Remove(selectedWords); 
     } 
    } 

如何使用刪除語法?

回答

0

你必須使用ctx.Words.Remove(word);

+0

的int從CTX刪除數據的wordID = 2; var selectedWords =(從上下文中的o.Addresses where o.word == wordId select 0).FirstOrDefault();我測試這種方式,但給了我錯誤 – motevalizadeh 2013-02-14 11:36:20

+0

@motevallizadeh:什麼錯誤? – 2013-02-14 11:37:21

+0

錯誤\t \t 1爲最好重載方法匹配 'System.Data.Entity.DbSet 卸下襬臂(ConsoleApplication2.words)' 具有一些無效參數\t G:\ XXX/Program.cs的\t ConsoleApplication2 – motevalizadeh 2013-02-14 11:38:49

1

使用這一個:ctx.Words.Remove(字)。並且不要忘記SaveChanges();在處理上下文之前。 !!!!!!!我已經更新了答案!!!!!! 這個isue新的想法:

static void Main(string[] args) 
    { 
     using (var ctx = new HKDBEntities()) 
     { 
      int wordId=2; 
      // This will get the first Addresses which have a `Words` with `WordId`==2 
      var selectedWords = ctx.Addresses.First(e=>e.Words.WordId==wordId); 
      //If you want to get to selectedWords the `Words` entity and delete it you should use: 
      selectedWords = cts.Words.First(e=>e.WordId == wordId); 

      ctx.Words.Remove(selectedWords); 
      ctx.SaveChanges(); 
     } 
    } 

您試圖訪問,而你從上下文中獲取數據

+0

int wordId = 2; var selectedWords =(從上下文中的o.Addresses where o.word == wordId select 0).FirstOrDefault();我測試這種方式,但給了我錯誤 context.word.Remove(selectedWords); – motevalizadeh 2013-02-14 11:33:25

+0

你能寫出你得到的錯誤嗎? – Maris 2013-02-14 11:43:51

+0

您從錯誤的實體中刪除。試試這個ctx.Addresses.Remove(selectedWords); – Maris 2013-02-14 11:47:13