简体   繁体   English

实体框架不会向数据库添加新行

[英]Entity Framework does not add new row to database

Adding data to database on MVC 4.5 using Entity Framework. 使用实体框架在MVC 4.5上向数据库添加数据。 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. 您不需要Attach()ChangeObjectState() ,但确实需要将实体Add()到其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: DbSet.Attach页面上:

SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there. 因此,SaveChanges将不会尝试将附加的实体插入数据库中,因为假定该实体已经存在。

Also you can change EntryState of a Subject to Created, Updated or Deleted using DbContext (your db object, I guess). 您也可以使用DbContext (我想是您的db对象)将主题的EntryState更改为Created,Updated或Deleted。

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. MSDN有关更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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