非延迟加载

时间:2017-04-01 08:36:23

标签: asp.net entity-framework asp.net-web-api

我的模型看起来像这样。

public class TradeModel
{
    public int id { get; set; }

    public BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }

}

我想做的是。当我调用post请求时,我想发送一个现有baseProduct的id,而不是整个baseProductForm和正在创建的id。

我试过

    [Required]
    public int baseProductId { get; set; }

    [ForeignKey("baseProductId")]
    public virtual BaseProductModel baseProduct { get; set; }

这样的事情,但似乎没有用。

任何可能的解决方案?

1 个答案:

答案 0 :(得分:0)

你的模特:

public class TradeModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }
    public virtual BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}

您的ViewModel:

public class TradeViewModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}

现在你只能传递baseProductId:

public IActionResult(TradeViewModel model)
{
    // Your form will contain only the id anyway so the method below should work.
    // Replace that with your actual context
    //dbcontext.Trades.Add(new TradeModel { ... });
}