NETCoreで予約アプリケーションを作成しています。
予約は、予約と1対1の関係にあります。
どちらのモデルにもナビゲーション特性があります。
外部キー(OccupancyId
)がBooking
に設定されていないようです。2つの項目を別々の表に挿入するEFコア
編集:次のコードはうまくいくようです。代わりにこのコードを使用するときに
Occupancy newOccupancy = new Occupancy { AccommodationId = 12, DateIn = new DateTime(2017, 1, 18), DateOut = new DateTime(2017, 2, 18) };
ApplicationDbContext.Occupancies.Add(newOccupancy);
Booking newBooking = new Booking { AccommodationId = 12, BookingStatusId = 6, Capacity = 69, OccupancyId = newOccupancy.Id, Paid = true, ProfileId = 1, Remark = "Geen", Total = 0 };
ApplicationDbContext.Bookings.Add(newBooking);
はしかし、もはや
BookingViewModelApplicationDbContext.Occupancies.Add(model.Occupancy);
ApplicationDbContext.Bookings.Add(model.Booking);
がBookingController
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CityViewModel model)
{
var alert = new Alert();
try
{
if(!ModelState.IsValid) {
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.INVALID;
throw new Exception();
}
Occupancy newOccupancy = new Occupancy { AccommodationId = 12, DateIn = new DateTime(2017, 1, 18), DateOut = new DateTime(2017, 2, 18) };
ApplicationDbContext.Occupancies.Add(newOccupancy);
Booking newBooking = new Booking { AccommodationId = 12, BookingStatusId = 6, Capacity = 69, OccupancyId = newOccupancy.Id, Paid = true, ProfileId = 1, Remark = "Geen", Total = 0 };
ApplicationDbContext.Bookings.Add(newBooking);
if (await ApplicationDbContext.SaveChangesAsync() == 0)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.CREATENOK;
throw new Exception();
}
alert.Message = ApplicationDbContextMessage.CREATEOK;
alert.Type = AlertType.Success;
AddAlert(alert);
return RedirectToAction("Index");
}
catch(Exception ex)
{
alert.Type = AlertType.Error;
alert.ExceptionMessage = ex.Message;
//AddAlert(alert);
model = await ViewModel(model.City);
ModelState.AddModelError(string.Empty, alert.ExceptionMessage);
}
return View(model);
}
内のメソッドを作成して動いていないようにみえ
占有モデル
public class Occupancy : BaseEntity<Int64>
{
public DateTime DateIn { get; set; }
public DateTime DateOut { get; set; }
public OccupancyType OccupancyType { get; set; }
public Int64 AccommodationId { get; set; }
public Accommodation Accommodation { get; set; }
public Booking Booking { get; set; }
}
予約モデル
public class Booking : BaseEntity<Int64>
{
public int Capacity { get; set; }
public bool Paid { get; set; }
public Decimal Total { get; set; }
public string Remark { get; set; }
public Int64 ProfileId { get; set; }
public Profile Profile { get; set; }
public Int64 AccommodationId { get; set; }
public Accommodation Accommodation { get; set; }
public Int64 OccupancyId { get; set; }
public Occupancy Occupancy { get; set; }
public Int64 BookingStatusId { get; set; }
public BookingStatus BookingStatus { get; set; }
}
私は問題がコントローラ自体ではなく、誤ったマッピングであると思います。 – Xamthi
更新いただきありがとうございます。あなたの方法がうまくいっていることをうれしく思います! –