简体   繁体   中英

Entity Framework does not add new row to database

Adding data to database on MVC 4.5 using Entity Framework. I am using the code below to add data to the the table aa 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();

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM