【问题标题】:Load data from related entities using Entity Framework使用实体框架从相关实体加载数据
【发布时间】:2021-07-25 16:36:35
【问题描述】:

我有两张桌子product 和Images。他们有一对多的关系。我想在视图中显示产品名称及其所有相关图像,我正在使用存储库模式。我是 MVC 和 Linq 的新手,请帮忙。提前致谢。

这是我的代码....

public partial class tbl_Product
{
        public int pro_id { get; set; }
        public string pro_name { get; set; }
        public string pro_desc { get; set; }
        public string pro_model { get; set; }
        public string pro_dimensions { get; set; }
        public Nullable<int> pro_UnitsInStock { get; set; }
        public Nullable<double> pro_price { get; set; }
        public Nullable<double> pro_oldprice { get; set; }
  
        public virtual ICollection<tbl_Images> tbl_Images { get; set; }
}

ProductRepository 类:

public ProductDetail GetProductByID(int id)
{
    var product = this.storeDB.tbl_Product.Where(x => x.pro_id == id).FirstOrDefault();   
                                      
    return product;
}

【问题讨论】:

    标签: asp.net-mvc entity-framework repository-pattern


    【解决方案1】:

    只需添加Include 子句即可加载相关图片:

    public ProductDetail GetProductByID(int id)
    {
        var product = storeDB.tbl_Product
                             .Where(x => x.pro_id == id)
                             .Include(p => p.tbl_Images)
                             .FirstOrDefault();   
                                          
        return product;
    }
    

    【讨论】:

    • 非常感谢,现在我被困在将这些值发布到控制器方法中。因为 var product 无法返回 ProductDetail.....请帮助
    • 这是一个全新的问题 - 如果您提出要求 - 请同时发布所有相关详细信息(例如您的 ProductDetail 课程的定义),以便我们有机会实际提供帮助 - 谢谢!
    • 我已经发布了一个关于这个问题的新问题。谢谢
    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 2013-07-11
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多