【发布时间】:2017-11-20 14:09:51
【问题描述】:
我在我的 mvc 核心应用程序中使用实体框架。我也在使用依赖注入技术。现在我想获取新记录标识列的值。我将代码用作..
public interface IGenericRepositoryStudent<T> where T : class
{
void Add(T item);
}
public class GenericRepositoryStudent<T> : IGenericRepositoryStudent<T> where T : class
{
private eerp_studentContext _context;
private DbSet<T> _dbSet;
public GenericRepositoryStudent(eerp_studentContext context)
{
_context = context;
_dbSet = _context.Set<T>();
}
public void Add(T item)
{
_dbSet.Add(item);
_context.SaveChanges();
}
}
控制器:
public class StudentController : Controller
{
private IStudentRepository _dbSet;
public StudentController(IStudentRepository dbSet)
{
_dbSet = dbSet;
}
public long Add([FromBody]Student _student)
{
if (ModelState.IsValid)
{
_dbSet.Add(acJournal);
long _id = _student.id; // value of _id is always 0.
return _id;
}
}
}
【问题讨论】:
-
只有在对象实际保存到数据库后才回填id,只有在调用
SaveChanges之后才会发生,而不是在调用Add之后发生。但是,在每次调用 add 之后调用SaveChanges是一个非常糟糕的主意,因为这会导致生成更多的查询。默认情况下,EF 会尝试一次提交所有更改。
标签: entity-framework dependency-injection asp.net-core-mvc