0

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();
1
  • I re-worded your question to focus on Entity Framework instead of MVC, is this what you intended? Commented May 14, 2015 at 14:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

waht is the assebly reference to use the add method
does not contain a definition for 'add' and no extension method 'add' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?). this is the message i am getting
private cisielearningEntities db = new cisielearningEntities();
subjec us type subject_tbl
the version of entity framework that i am using i 4.5
|
1

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.

2 Comments

does not contain a definition for 'Entry' and no extension method 'Entry' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?). this is the error i am getting any ideas why.
1. What type of db object? 2. Do you have using System.Data.Entity?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.