【发布时间】:2019-09-03 21:44:17
【问题描述】:
我有这个管理餐厅和评论的页面。我可以完美地创建餐厅和评论,但是当我想将评论链接到餐厅中的集合时,从视图中获取它时会消失
这是我的餐厅模型,我想在其中存储每家餐厅的评论:
public class Restaurant
{
public int ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public float AverageRating { get; set; }
public DateTime Data { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
}
审查模型:
public class Review
{
public int ID { get; set; }
public int Rating { get; set; }
public string Body { get; set; }
public string ReviewerName { get; set; }
public int RestaurantID { get; set; }
public DateTime Data { get; set; }
}
API 帖子:
public IActionResult Post(ReviewDTO r)
{
try
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
else
{
Review review = _mapper.Map<ReviewDTO, Review>(r);
//review.Restaurant = _restaurantAppService.Find(review.RestaurantID);
_reviewAppService.Add(review);
//_restaurantAppService.Find(review.RestaurantID).Reviews.Add(review);
_restaurantAppService.Average(_restaurantAppService.Find(review.RestaurantID));
return Ok();
}
}
catch (Exception ex)
{
//Log.Log.Error("Api error - Review - Post::" + ex.Message + "::" + ex.InnerException.Message + "::" + ex.InnerException.InnerException.Message);
throw new Exception("Error Api - Review - Post \n", ex);
}
}
最后是存储库:
public void Add(TEntity e)
{
try
{
db.Set<TEntity>().Add(e);
db.SaveChanges();
}
catch (Exception ex)
{
throw new Exception("Error in Infra.DATA - Add" + ex.Message, ex);
}
}
public IEnumerable<TEntity> All()
{
try
{
return db.Set<TEntity>().AsNoTracking().ToList();
}
catch (Exception ex)
{
throw new Exception("Error in Infra.DATA - All", ex);
}
}
那么问题来了:
- 评论已创建
- API 调用应用程序方法
- 实体类将评论插入数据库
- api调用应用方法将评论插入到餐厅列表'reviews'中
- 评论插入成功,调试可以看到数据库中餐厅更新了评论插入
- 控制器发回餐厅以查看餐厅的详细信息,其中列出了其评论,但在此 步骤,评论丢失并设置为空。
我可以编辑、删除和创建餐厅和评论,但我无法将它们与餐厅一起存储。
我在框架而不是核心中完成了同样的项目并且没有问题,有人知道为什么会发生这种情况吗?
【问题讨论】:
-
可以在选择餐厅的地方添加控制器/服务代码吗?
标签: c# entity-framework asp.net-core-mvc