我有两个实体
public class ProductOption
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OptionId { get; set; }
[Required]
[MaxLength(40)]
public String OptionName { get; set; }
}
public class ProductOptionValue
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ValueId { get; set; }
public int OptionId { get; set; }
[Required]
[MaxLength(32)]
public String ValueName { get; set; }
}
以上实体
我有2个模型类
public class ProductOptionRequest
{
public string Name { set; get; }
public List<ProductValuesRequest> productValues { get; set; }
}
public class ProductValuesRequest
{
public int OptionId { get; set; }
public string ValueName { get; set;}
}
现在我想将数据插入那些表中
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
ReturnString returnString = new ReturnString();
ProductOption details = new ProductOption();
details.OptionName = request.Name;
object result = await productOptionRepository.InsertAsync(details, true);
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOptionValue res = new ProductOptionValue();
res.OptionId = valueRequest.OptionId;
res.ValueName = valueRequest.ValueName;
object response = await productOptionValueRepository.InsertAsync(res, true);
}
returnString.StringValue = result != null ? $"{request.Name} saved successfully" : "";
return returnString;
}
我写了上面的模式。但我不想通过OptionId
。如何在不传递OptionId
参数的情况下编写单个插入查询。因为它是ProductOption
表的外键。
答案 0 :(得分:0)
//请尝试此代码。
public class ProductOptionValue
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ValueId { get; set; }
public int OptionId { get; set; }
[Required]
[MaxLength(32)]
public String ValueName { get; set; }
[RelatedField(Table = "ProductOption", ForeignKey = "OptionId", PrimaryKey="Id")]
public ProductOption ProductOption{ get; set; }
}
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
ReturnString returnString = new ReturnString();
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOption details = new ProductOption();
details.OptionName = request.Name;
ProductOptionValue res = new ProductOptionValue();
res.ValueName = valueRequest.ValueName;
res.ProductOption =result ;
object response = await
productOptionValueRepository.InsertAsync(res, true);
}
returnString.StringValue = result != null ? $"{request.Name} saved successfully" : "";
return returnString;
}