我有一个简单的api方法将数据插入db,邮递员man中的方法显示成功,但数据未插入数据库中,这是我的代码
private Utilities uti = new Utilities();
private readonly ApplicationDBContext db;
public AppraisalController(ApplicationDBContext context)
{
db = context;
}
//INSERT API FOR AppraisalIdentity table
[AllowAnonymous]
[Route("api/appraiseinsert")]
[HttpPost]
public IActionResult Create([FromBody] AppraisalIdentity cre)
{
if (cre == null)
{
return BadRequest();
}
using (var transaction = db.Database.BeginTransaction())
{
try
{
#region Appraisal Insert
var apprais = new AppraisalIdentity
{
AppraisalName = cre.AppraisalName,
IsCurrent = cre.IsCurrent,
CompanyID = cre.CompanyID,
DateAdded = cre.DateAdded
};
db.AppraisalIdentity.Add(apprais);
db.SaveChanges();
#endregion
}
catch (Exception ex)
{
transaction.Rollback();
return Json(new
{
statusCode = ex.Message
});
}
}
return Json(new
{
statusCode = "Success"
});
}
我不知道,也许我的代码中有一个我不知道的错误,但事实是在邮递员中,api返回了成功,但未在db中插入任何内容。谢谢
答案 0 :(得分:4)
由于您正在使用事务,所以我猜您需要在调用db.SaveChanges()之后提交事务,如下所示:
db.SaveChanges();
transaction.Commit();