2015-01-13 48 views
0

我正在使用MVC5。我在Index.cshtml中有一個SQL數據工作表。刪除並更新MVC5中的SQL表

我有一個由五個元素組成的簡單SQL表,testID是沒有錯誤的主鍵。

我想在這裏做的是刪除一行數據並讓它更新SQL表。

Index.cshtml

<center> 
<table> 
    <tr><td colspan="5" align="center"><br /><br /><h1>Table1 Printout</h1></td></tr> 
    <tr><td align="center">testID</td><td align="center">datetime</td><td align="center">col1</td><td align="center">col2</td><td align="center">col3</td><td></td></tr> 
    @foreach (var item in Model.thistable) 
    { 
     <tr><td>@item.testID</td><td>@item.datetime</td><td>@item.col1</td><td>@item.col2</td><td>@item.col3</td><td><form action="@Url.Action("Delete", new{ testID = @item.testID})" method="delete"><input type="submit" value="Delete" /></form></td></tr> 
    } 
</table> 
</center> 

HomeController.cs

public ActionResult Delete(int id) 
    { 
     Table1.Remove(Table1.SingleOrDefault(o => o.testID == id)); 
     return RedirectToAction("uvm"); 
    } 

Class.cs

public class Table1 
{ 
    [Key] 
    public int testID { get; set; } 
    public string datetime { get; set; } 
    public string col1 { get; set; } 
    public string col2 { get; set; } 
    public string col3 { get; set; } 
} 
public class UserViewModel 
{ 
    public string errorcode { get; set; } 
    public List<Table1> thistable { get; set; } 
} 

回答

2

你必須調用SaveChanges()方法來複制你在已更改數據庫模型。 此外,您還需要更改DbContext中的實體。

Entities ent = new Entities(); //This is name of DbConetxt Class 
ent.Table1.Remove(ent.Table1.SingleOrDefault(o => o.testID == id)); 
ent.SaveChanges(); 
+0

我也遇到了「刪除」和「SingleOrDefault」的問題MVC5遇到了這些問題。 – ematica

+0

有什麼問題? – Mairaj

+0

表1不包含Remove或SingleOrDefault的定義。你如何在Table1中定義它們? – ematica