【问题标题】:How to get One Table data on the basis of ID from another table如何根据ID从另一个表中获取一个表数据
【发布时间】:2019-05-12 07:57:30
【问题描述】:

我创建了 3 个表关系(用户、项目、产品)

一个用户有很多项目,一个项目有很多产品(一对多)

我需要在用户登录时显示所有项目和包含的产品

我已经使用以下代码完成了它,但我认为这不是处理它的最佳方法。我需要做得更好

public ActionResult Index()
    {

        ModulesViewModel mvm = new ModulesViewModel();
        List<Modules> modules = new List<Modules>();
        var userId = User.Identity.GetUserId();
        var projects = _adsDbContext.Project.Where(x=>x.UserID == userId).ToList();
        foreach (var pro in projects)
        {

            var productData = _adsDbContext.Product.Where(x => x.ProjectID == pro.ProjectID); 
            modules.AddRange(productData);

        }
        modules = modules.OrderBy(x => x.ProjectID).OrderBy(x=>x.ModuleNumber).ToList();
        mvm.Modules = modules;
        return View(mvm);
    }

public class Project
{
    public int ProjectID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductData> Products { get; set; }


    public string UserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

public class ProductData : Modules
{
    public int ProductDataID { get; set; }
    public float ConversionRate { get; set; }
    public float Price { get; set; }
    public float TotalSales { get; set; }
    public float GrossSales { get; set; }
    public float NetProfit { get; set; }
    public float ProfitPerLead { get; set; }
}


public abstract class Modules
{

    public int ProjectID { get; set; }
    public virtual Project Project { get; set; }
}

这很好,但我需要以更好的方式来做,而不是从头开始创建关系或使查询更好。

【问题讨论】:

    标签: c# entity-framework linq relationship


    【解决方案1】:

    您的模型包含项目每一端到产品一对多关系的导航属性。

    这允许您从项目开始查询,应用过滤器,然后使用集合导航属性和SelectMany“向下导航”:

    var modules = _adsDbContext.Project
        .Where(x => x.UserID == userId)
        .SelectMany(x => x.Products) // <--
        .OrderBy(x => x.ProjectID).ThenBy(x => x.ModuleNumber)
        .ToList<Modules>();
    

    或者您可以从产品开始查询并使用参考导航属性“导航”向上以应用过滤器:

    var modules = _adsDbContext.Product
        .Where(x => x.Project.UserID == userId) // <--
        .OrderBy(x => x.ProjectID).ThenBy(x => x.ModuleNumber)
        .ToList<Modules>();
    

    【讨论】:

    • 感谢您的回复,我遇到的另一个问题是:我使用模块作为产品和其他类型的基类,因此我将所有不同的模块一一获取并将其添加到模块列表中,然后在前端,我在模块上进行迭代,需要显式转换为子项,然后显示详细信息,我可以做得更好吗?
    • 如果没有创建项目,我还需要一次保存项目和产品,如果创建了项目,则只更新产品
    • 恐怕我们无法在一篇文章中涵盖多个问题。上述答案基于您帖子中的用例和代码。如果您有其他问题/用例,请创建单独的问题并清楚地解释它们以及目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多