【问题标题】:Non lazy loading非延迟加载
【发布时间】:2017-04-01 08:36:23
【问题描述】:

我有一个这样的模型。

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; }

}

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

试过了

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

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

类似的东西,但似乎不起作用。

任何可能的解决方案?

【问题讨论】:

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


    【解决方案1】:

    你的模特:

    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; }
    }
    

    您的视图模型:

    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 { ... });
    }
    

    【讨论】:

    • 我的意思是我已经尝试使用外键和虚拟的东西,但它仍然会显示并需要虚拟属性
    • 您是将当前模型传递给视图还是创建了一个单独的视图模型?
    猜你喜欢
    • 2012-05-21
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2021-07-13
    相关资源
    最近更新 更多