使用entity framework模型插入数据

我试图插入一些数据在我的数据库使用entity framework模型,但由于一些未知的原因给我,它什么都不做。

我在这里错过了什么?

using (var context = new DatabaseEntities()) { var t = new test { ID = Guid.NewGuid(), name = "blah", }; context.AddTotest(t); context.SaveChanges(); } 

它应该是:

 context.TableName.AddObject(TableEntityInstance); 

哪里:

  1. TableName :数据库中表的名称。
  2. TableEntityInstance :表实体类的一个实例。

如果你的表是Orders ,那么:

 Order order = new Order(); context.Orders.AddObject(order); 

例如:

  var id = Guid.NewGuid(); // insert using (var db = new EfContext("name=EfSample")) { var customers = db.Set<Customer>(); customers.Add( new Customer { CustomerId = id, Name = "John Doe" } ); db.SaveChanges(); } 

这是一个生动的例子:

 public void UpdatePlayerScreen(byte[] imageBytes, string installationKey) { var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault(); var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault(); if (current != null) { current.Screen = imageBytes; current.Refreshed = DateTime.Now; this.ObjectContext.SaveChanges(); } else { Screenshot screenshot = new Screenshot(); screenshot.ID = Guid.NewGuid(); screenshot.Interval = 1000; screenshot.IsTurnedOn = true; screenshot.PlayerID = player.ID; screenshot.Refreshed = DateTime.Now; screenshot.Screen = imageBytes; this.ObjectContext.Screenshots.AddObject(screenshot); this.ObjectContext.SaveChanges(); } } 
 var context = new DatabaseEntities(); var t = new test //Make sure you have a table called test in DB { ID = Guid.NewGuid(), name = "blah", }; context.test.Add(t); context.SaveChanges(); 

应该这样做

[HttpPost] //在button点击事件时编写逻辑时使用它

 public ActionResult DemoInsert(EmployeeModel emp) { Employee emptbl = new Employee();// make object of table emptbl.EmpName = emp.EmpName; emptbl.EmpAddress = emp.EmpAddress; //add if any field you want insert dbc.Employees.Add(emptbl);pass the table object dbc.SaveChanges(); return View(); } 

我使用的是EF6,我发现一些奇怪的东西,

假设Customer具有带参数的构造函数,

如果我使用new Customer(id, "name") ,并做

  using (var db = new EfContext("name=EfSample")) { db.Customers.Add( new Customer(id, "name") ); db.SaveChanges(); } 

它运行没有错误,但是当我看着数据库,我发现其实数据不是插入,

但是,如果我添加大括号,使用new Customer(id, "name"){}并做

  using (var db = new EfContext("name=EfSample")) { db.Customers.Add( new Customer(id, "name"){} ); db.SaveChanges(); } 

数据将被实际插入,

似乎花括号做出了区别,我猜测只有在添加Curly Brackets时,entity framework才会认识到这是一个真实的具体数据。