SaveChanges()不会在Visual Studio c#中更新实际的表数据
本文关键字:更新 数据 Studio Visual SaveChanges | 更新日期: 2023-09-27 18:11:17
不管什么原因,这段代码只能在程序运行时工作。它更新db中的一行。,并将其打印到列表框中。但是一旦退出,数据库中就没有该表的表数据了。它根本不会保存更改。
private void button1_Click(object sender, EventArgs e)
{
Database1Entities db = new Database1Entities();
var st = new Student { StudentID = 1, StudentName = "Jack" };
db.Students.Attach(st);
db.Students.Add(st);
db.SaveChanges();
foreach (Student s in db.Students)
listBox1.Items.Add(s.StudentName);
}
编辑-这是我的上下文:
//--------------------------------------------------------------------------
----
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApplication4
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class Database1Entities1 : DbContext
{
public Database1Entities1()
: base("name=Database1Entities1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Student> Students { get; set; }
}
}
private void button1_Click(object sender, EventArgs e)
{
Database1Entities db = new Database1Entities();
var st = new Student { StudentName = "Jack" };
db.Students.Add(st);
db.SaveChanges();
foreach (Student s in db.Students)
listBox1.Items.Add(s.StudentName);
}
删除:
db.Students.Attach(st);
有关附加操作的更多信息,请阅读:
https://msdn.microsoft.com/en-us/data/jj592676.aspx