使用实体框架模型插入数据

我试图使用实体框架模型在数据库中插入一些数据,但是由于一些未知的原因,它什么也不做。

我错过了什么吗?

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

It should be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName: the name of the table in the database.
  2. TableEntityInstance: an instance of the table entity class.

If your table is Orders, then:

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

For example:

 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();
}

Here is an example:

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();

Should do it

[HttpPost] // it use when you write logic on button click event

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();
}

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

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

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

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

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.