当我尝试将数据放入“AccomodationCategories”表中时,我遇到了一个问题,但是我遇到了错误:
Npgsql.PostgresException:42P01:关系“AccomodationCategories”不存在
所以这就是我的表格:
当我保存我的“住宿”时,我在下拉列表中从“类别”表中选择一个类别。但是当我点击更新时它会出错。
这是我在AccomodationController中的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(AccomodationDetailViewModel model, Int16 id)
{
var alert = new Alert();
try
{
if(!ModelState.IsValid)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.INVALID;
throw new Exception();
}
var originalModel = ApplicationDbContext.AccomodationDetails.FirstOrDefault(m => m.Id == model.AccomodationDetail.Id);
//AccomodationCategories
var modelC = await ApplicationDbContext.AccomodationCategories.FirstOrDefaultAsync(m => m.AccomodationId == id);
var modelC2 = await ApplicationDbContext.AccomodationCategories.FirstOrDefaultAsync(m => m.CategoryId == id);
var accoCat1 = ApplicationDbContext.AccomodationCategories.FirstOrDefault(m => m.AccomodationId == modelC.Accomodations.Id);
var accoCat2 = ApplicationDbContext.AccomodationCategories.FirstOrDefault(m => m.CategoryId == modelC2.Categories.Id);
//
if(originalModel == null)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.NOTEXISTS;
throw new Exception();
}
originalModel.Title = model.AccomodationDetail.Title;
originalModel.Description = model.AccomodationDetail.Description;
originalModel.RentalTypeId = model.AccomodationDetail.RentalTypeId;
//AccomodationCategories
accoCat1.AccomodationId = modelC.AccomodationId;
accoCat2.CategoryId = modelC2.CategoryId;
ApplicationDbContext.AccomodationCategories.Attach(accoCat1);
ApplicationDbContext.AccomodationCategories.Attach(accoCat2);
//
ApplicationDbContext.AccomodationDetails.Attach(originalModel);
ApplicationDbContext.Entry(originalModel).State = EntityState.Modified;
if (await ApplicationDbContext.SaveChangesAsync() == 0)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.EDITNOK;
throw new Exception();
}
alert.Message = ApplicationDbContextMessage.EDITOK;
return RedirectToAction("Index");
}
catch(Exception ex)
{
alert.Type = AlertType.Error;
alert.ExceptionMessage = ex.Message;
model = await ViewModel(model.AccomodationDetail);
ModelState.AddModelError(string.Empty, alert.ExceptionMessage);
}
return View(model);
}
这是我的ApplicationDbContext.cs中的代码
public DbSet<AccomodationCategory> AccomodationCategories { get; set; }
// Many-To-Many in EF7 (10-10-2016)
// Accomodation can have many categories
// category can be assigned to many Accomodations
builder.Entity<AccomodationCategory>()
.HasKey(c => new { c.AccomodationId, c.CategoryId });
builder.Entity<AccomodationCategory>()
.HasOne(ac => ac.Accomodations)
.WithMany(p => p.Categories)
.HasForeignKey(ac => ac.AccomodationId);
builder.Entity<AccomodationCategory>()
.HasOne(ac => ac.Categories)
.WithMany(a => a.Accomodations)
.HasForeignKey(ac => ac.CategoryId);