My application allows the user to create products along with their UOM (Units of Measurement) and Barcodes
During the creation process, API will check if there is no barcode entered, it will generate it automatically. That worked fine until I decided to add weight products that require scale barcodes with 7 digits. BeforeSaveEntity will ask if the product type is weight then generate 7 digits barcode, else, it will generate 13 digits.
The problem is; I can't get this to work when checking the parent table, here is my code:
Models: (for convenience, I have omitted unneeded properties.)
public class Product
{ public int Id { get; set; }
public ProductName { get; set; }
public int ClassId { get; set; }
public ICollection<Unit> Units { get; set; }
}
public class Unit
{
public int Id { get; set; }
[ForeignKey("Product")]
public int ProdId { get; set; }
public int PackId { get; set; }
public decimal PackUnits { get; set; }
public Product Product { get; set; }
public ICollection<Barcode> Barcodes { get; set; }
}
public class Barcode
{
public int Id { get; set; }
[ForeignKey("Unit")]
public int UnitId { get; set; }
public string Bcode { get; set; }
[DefaultValue("false")]
public bool IsSystemGenerated { get; set; }
public Unit Unit { get; set; }
}
Before Save Entity:
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
if (entityInfo.Entity.GetType() == typeof(Barcode)
&& (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Added || entityInfo.EntityState == Breeze.ContextProvider.EntityState.Modified))
{
var barcode = (Barcode)entityInfo.Entity;
var product = (Product)barcode.Unit.Product; // The problem is here
int classId = product.ClassId;// Hence, can't get this guy
string bcode = barcode.Bcode;
if (String.IsNullOrEmpty(bcode))
{
if (classId != 2) // Check if the product type is not weight
barcode.Bcode = GenerateBarcode();
else // Otherwise generate scale barcode
barcode.Bcode = GenerateScaleBarcode();
barcode.IsSystemGenerated = true;
}
return true;
}
else
return true;
}
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap)
{
return saveMap;
}
Acquiring the parent navigation property Product gives an error message:
Object reference not set to an instance of an object
Disabling the classId checking, Insert takes place in the following order: Product => Unit => Barcode which in this case, Barcode entity should give information on it's parents Unit then Product.