我创建了一个对字段使用不同枚举的类。当我在控制器中创建该类类型的对象时,我需要知道该字段并使用它来确定最终数量,然后再将该对象保存到控制器中。它将作为布尔值求值,对于除Stuff = 0之外的任何值都另存为零。
枚举
public enum StuffMeasureSystem
{
Stuff = 0,
[Display(Name = "16\" Stuff")]
Stuff16 = 1,
[Display(Name = "24\" Stuff")]
Stuff24 = 2
}
班级
public class Stuff
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; set; }
[JsonIgnore]
public Company Company { get; set; }
public Guid CompanyId { get; set; }
[JsonIgnore]
public ApplicationUser CreatedBy { get; set; }
public string CreatedById { get; set; }
public StuffMeasureSystem MeasureSystem { get; set; }
public double Quantity { get; set; }
public double Quantity_Stuff_16 (double Quantity)
{
return Quantity * (1 / 3);
}
public double Quantity_Stuff_24(double Quantity)
{
return Quantity * .5;
}
public Location Location { get; set; }
public int? LocationId { get; set; }
}
控制器
if (ModelState.IsValid)
{
if (stuff.MeasureSystem == StuffMeasureSystem.Stuff16)
{
stuff.Quantity = stuff.Quantity_Stuff_16(stuff.Quantity);
}
else if (stuff.MeasureSystem == StuffMeasureSystem.Stuff24)
{
stuff.Quantity = stuff.Quantity_Stuff_24(stuff.Quantity);
}
else
{
stuff.Quantity = stuff.Quantity;
}
_context.Add(stuff);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}