0
我有一個創紀錄的課程和一個汽車班。一個記錄可以有多輛車。我試圖使用RecordID作爲兩者之間的關鍵。在第一種觀點中,我的表格填補了記錄類的模型。然後,我想要採取不同的觀點,並將汽車添加到記錄中。一旦我導航到第二個視圖,我怎麼能告訴記錄ID使用的汽車?我正在閱讀有關ViewModels和Unit of Work等內容。不確定的差異和/或如果這些是我正在尋找。我將包含我的模型和存儲庫方法中的一些代碼。謝謝!如何從單獨的視圖發佈一對多關係?
Record.cs
namespace Train.Models {
public class Record {
public int RecordId { get; set; }
public int Quantity { get; set; }
public DateTime DateCreated { get; set; }
public bool IsActive { get; set; }
public string UserId { get; set; }
public virtual ICollection<Cars> Cars { get; set; }
}
}
Cars.cs
namespace Train.Models {
public class Cars {
public int Id { get; set; }
public string EmptyOrLoaded { get; set; }
public string CarType { get; set; }
//Hopper, flatbed, tank, gondola, etc.
public string ShippedBy { get; set; }
//UP(Union Pacific) or BNSF
public string RailcarNumber { get; set; }
//public virtual ApplicationUser ApplicationUser { get; set; }
public string UserId { get; set; }
public virtual Record Record { get; set; }
}
}
RecordRepository.cs
public void SaveRecord(Record recordToSave) {
if (recordToSave.RecordId == 0) {
recordToSave.DateCreated = DateTime.Now;
_db.Record.Add(recordToSave);
_db.SaveChanges();
} else {
var original = this._db.Record.Find(recordToSave.RecordId);
original.Quantity = recordToSave.Quantity;
original.IsActive = true;
_db.SaveChanges();
}
}
CarsRepository.cs
public void SaveCar(Cars carToSave) {
if (carToSave.Id == 0) {
_db.Cars.Add(carToSave);
_db.SaveChanges();
} else {
var original = this.Find(carToSave.Id);
original.EmptyOrLoaded = carToSave.EmptyOrLoaded;
original.CarType = carToSave.CarType;
original.ShippedBy = carToSave.ShippedBy;
original.RailcarNumber = carToSave.RailcarNumber;
_db.SaveChanges();
}
}
太棒了,非常感謝!我對ForeignKey有問題。它不會讓我使用RecordId,因爲它是空的,它不能爲空。 – ScottVMeyers