sha*_*Hwk 4 c# asp.net asp.net-mvc entity-framework ef-code-first
我需要知道如何更新和删除数据库中的记录.我知道如何添加记录但无法更新和删除数据库中的记录.
namespace Ex.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    public partial class MyEntities : DbContext
    {
        public MyEntities()
            : base("name= MyEntities")
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        public DbSet<Friend> Friend { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)
-
控制器
// POST: /Home/Edit/5
[HttpPost]
public ActionResult Edit(int id, Friend f)
{
    try
    {
        // TODO: Add update logic here
        myEntities.Friend.Attach(f);// Doesn't work.. How to update ?
        myEntities.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)
要将记录添加到数据库,我使用以下代码.有效;
myEntities.Friend.Add(f);
myEntities.SaveChanges();
return RedirectToAction("Index");
Run Code Online (Sandbox Code Playgroud)
UPDATE
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Exp.Models.Friend>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Delete
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Delete</h2>
<h3>Are you sure you want to delete?</h3>
<fieldset>
    <legend>Friend</legend>
    <div class="display-label">Name</div>
    <div class="display-field">
        <%: Html.DisplayFor(model => model.Name) %>
    </div>
</fieldset>
<% using (Html.BeginForm()) { %>
    <p>
        <input type="submit" value="Delete" /> |
        <%: Html.ActionLink("Back to List", "Index") %>
    </p>
<% } %>
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
    删除
myEntities.Friend.Remove(f);
myEntities.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
更新
Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId);
f.Name = NewName;
myEntities.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           47217 次  |  
        
|   最近记录:  |