我有一个名为 VendorReader 的多对多实体,它看起来像这样:
public partial class VendorReader
{
public int ID { get; set; }
public int VendorID { get; set; }
public string AssetValue { get; set; }
public virtual Vendor Vendor { get; set; }
public virtual AssetReader AssetReader { get; set; }
}
我有一个 VendorReader 的存储库,它看起来像这样:
public class VendorReaderRepository : Repository<VendorReader>
{
public VendorReaderRepository() { }
public VendorReaderRepository(EventBadgesEntities ctx) : base(ctx) { }
public List<VendorReader> GetVendorReadersByEventID(int eventID)
{
return ctx.VendorReaders
.Where(e => e.Vendor.EventID == eventID)
.ToList();
}
public int GetVendorIDByReaderSN(string readerSN) {
VendorReader thisList = ctx.VendorReaders
.Where(e => e.AssetReader.ReaderSN == readerSN)
.SingleOrDefault();
return thisList.VendorID;
}
}
在我的代码中,我这样做:
thisVendorReader.VendorID = model.AddEditVendorReader.VendorID;
thisVendorReader.AssetValue = model.AddEditVendorReader.AssetValue;
vrr.Add(thisVendorReader);
在基本存储库中执行此操作:
public T Add(T entity)
{
ctx.Set<T>().Add(entity);
ctx.SaveChanges();
return entity;
}
然后我尝试这样做:
model = new MapVendorModel(model.EventID);
这样做:
public MapVendorModel(int eventID)
{
// steps to create a selectlist
VendorRepository vr = new VendorRepository();
listVendor = vr.GetVendorsByEventID(eventID)
.ToList()
.OrderBy(x => x.VendorName)
.ToSelectList(x => x.VendorName, x => x.ID.ToString(), null)
.ToList();
EventID = eventID;
// now let's get the vendor reader list
VendorReaderRepository mvmVrr = new VendorReaderRepository();
VendorReaderList = mvmVrr.GetVendorReadersByEventID(eventID)
.ToList()
.OrderBy(x => x.Vendor.VendorName)
.ToList();
}
但是当我这样做时,我在 x.Vendor.VendorName b/c 上收到 Null Reference Exception 错误,似乎在对象中找不到添加的新供应商。我已经研究过,我想出的只是 SaveChanges 应该修复它。这在我添加 AssetReader 之前没有发生,它存储了 Reader 的实际 SN(出于各种原因我需要它)。