Reputation: 177
Adding data to database on MVC 4.5 using Entity Framework. I am using the code below to add data to the the table a a new row the candidate may contain, will not be adding the entire row. I would like to know why this is not working, I get no compile or runtime errors.
var subject = db.subjects_tbl;
var sub = subject.CreateObject();
sub.subject_title = model.subject_title;
sub.language_Id = model.language_Id;
db.subjects_tbl.Attach(sub);
db.ObjectStateManager.ChangeObjectState(sub, EntityState.Added);
db.SaveChanges();
Upvotes: 0
Views: 6044
Reputation: 471
Also you can change EntryState
of a Subject to Created, Updated or Deleted using DbContext
(your db
object, I guess).
var subject = db.subjects_tbl;
var sub = subject.CreateObject();
sub.subject_title = model.subject_title;
sub.language_Id = model.language_Id;
db.Entry(sub).State = EntityState.Added;
db.SaveChanges();
MSDN For more details.
Upvotes: 1
Reputation: 273244
You don't need the Attach()
and ChangeObjectState()
, but you do need to Add()
an entity to its DbSet.
var sub = subject.CreateObject();
sub.subject_title = model.subject_title;
sub.language_Id = model.language_Id;
//db.subjects_tbl.Attach(sub);
//db.ObjectStateManager.ChangeObjectState(sub, EntityState.Added);
db.subjects_tbl.Add(sub);
db.SaveChanges();
From the DbSet.Attach page:
SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there.
Upvotes: 3