I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities())
{
var t = new test
{
ID = Guid.NewGuid(),
name = "blah",
};
context.AddTotest(t);
context.SaveChanges();
}
This question is related to
c#
.net
entity-framework
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.
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();
}
Source: Stackoverflow.com