我有一个记录课和一个汽车课。一条记录可以有多辆车。我试图使用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();
}
}
答案 0 :(得分:1)
您必须为记录ID的车型设置外键。只需在RecordID的汽车模型中添加另一列。
插入记录后,您必须返回插入的ID并将此记录ID设置为car对象,然后再将其保存到数据库中。
public void AddCars(int recordID, List<Cars> carsToSave) {
foreach(Cars car in carsToSave){
car.RecordID = recordID;
_db.Cars.Add(car);
}
_db.SaveChanges();
}
public void EditCars(List<Cars> carsToEdit){
foreach(Cars car in carsToEdit){
Cars editCar = this.Find(car.Id);
editCar.EmptyOrLoaded = car.EmptyOrLoaded;
editCar.CarType = car.CarType;
editCar.ShippedBy = car.ShippedBy;
editCar.RailcarNumber = car.RailcarNumber;
editCar.ApplicationUser = car.ApplicationUser;
editCar.UserId = car.UserId;
_db.SaveChanges();
}
}