我正在尝试跟踪汽车零件是否在当地总部和州总部之间被记录为已维修。我在零件表中获得了一个名为 Car_Vin 的附加字段。此外,当我获取与汽车相关的记录时,我的记录集合总是以空的形式返回。有人可以解释为什么会发生这两个问题吗?
public Car
{
[Key]
public string VIN{get;set;}
//More fields go here
public virtual ICollection<StateHQRecord> StateHQRecords{get;set;}
public virtual ICollection<LocalHQRecord> LocalHQRecords{get;set;}
}
public Part{
{
[Key]
public string PartNumber{get;set;}
//More fields go here
public virtual ICollection<StateHQRecord> StateHQRecords{get;set;}
public virtual ICollection<LocalHQRecord> LocalHQRecords{get;set;}
}
public class StateHQRecord
{
public string VIN{get;set;}
public string PartNumber{get;set;}
public Car Car{get;set;}
public Part Part{get;set;}
public bool isRepaired{get;set;}
}
public class LocalHQRecord
{
public string VIN{get;set;}
public string PartNumber{get;set;}
public Car Car{get;set;}
public Part Part{get;set;}
public bool isRepaired{get;set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StateHQRecord>().HasKey(te => new {te.VIN, te.PartNumber});
modelBuilder.Entity<StateHQRecord>().Map(m => m.ToTable("StateHQRecords"));
modelBuilder.Entity<LocalHQRecord>().HasKey(te => new {te.VIN, te.PartNumber});
modelBuilder.Entity<LocalHQRecord>().Map(m => m.ToTable("LocalHQRecords"));
modelBuilder.Entity<Car>().HasKey(a => a.VIN);
modelBuilder.Entity<Car>().
HasMany(a => a.StateHQRecords).
WithRequired(te => te.Car).
HasForeignKey(te => te.VIN);
modelBuilder.Entity<Car>().
HasMany(a => a.LocalHQRecords).
WithRequired(te => te.Car).
HasForeignKey(te => te.VIN);
modelBuilder.Entity<Part>().HasKey(a => a.PartNumber);
modelBuilder.Entity<Part>().
HasMany(a => a.StateHQRecords).
WithRequired(te => te.Part).
HasForeignKey(te => te.PartNumber);
modelBuilder.Entity<Part>().
HasMany(a => a.LocalHQRecords).
WithRequired(te => te.Part).
HasForeignKey(te => te.PartNumber);
}
public void AddCarToLocalHQ(Car car,Part part)
{
var currentCarEntityState=EntityState.Modified;
var currentPartEntityState=EntityState.Modified;
var currentCar=context.Cars.FirstOrDefault(c=>c.VIN==car.VIN);
var currentPart=context.Parts.FirstOrDefault(p=>p.PartNumber==part.PartNumber);
if(currentCar==null)
{
currentCar=car;
currentCarEntityState=EntityState.Added;
}
if(currentPart==null)
{
currentPart=part;
currentPartEntityState=EntityState.Added;
}
var currentRecord=context.LocalHQRecords.FirstOrDefault(r=>r.VIN==currentCar.VIN && r.PartNumber==currentPart.PartNumber);
if(currentRecord!=null)
{
throw new DuplicateRecordException();
}
currentRecord=new LocalHQRecord{Car=currentCar,Part=currentPart};
currentCar.LocalHQRecords.Add(currentRecord);
currentPart.LocalHQRecords.Add(currentRecord);
context.Entry(currentCar).State=currentCarEntityState;
context.Entry(currentPart).State=currentPartEntityState;
context.SaveChanges();
}