如何使用linq和实体框架连接表格?

问题描述 投票:0回答:1

在下面的代码中,我想加入所有三个表,我得到的数据通过加入表,但在显示数据时,只有CK_Model的数据显示。请帮助

public List<CK_Model> GetDetails()
    {
        try
        {
            using (var entities = new MobileStore2020Entities())
            {
                var details = from a in entities.CK_Model
                              join b in entities.CK_Brand
                              on a.BrandID equals b.BrandID
                              join c in entities.CK_Stock
                              on a.ModelID equals c.ModelID
                              select new 

                              {
                                  ModelID = a.ModelID,
                                  ModelName = a.ModelName
                              };
                return details.ToList();

谢谢你。

entity-framework linq join
1个回答
0
投票

如果我的理解是正确的,你想通过你的上下文访问所有三个表来返回数据。如果你想这样做,你必须改变你的方法的返回类型。例如,创建一个新的类,包含所有的3个项目类型

public class DetailsItemType
{
     public CK_Model Model{ get; set; }
     public CK_Brand Brand { get; set; }
     public CK_Stock Stock { get; set; }
}

然后将你的方法的返回类型改为DetailsItemType,你将会有类似下面的东西。

public List<DetailsItemType> GetDetails()
{
    using (var entities = new MobileStore2020Entities())
    {
        var details = from a in entities.CK_Model
                      join b in entities.CK_Brand
                      on a.BrandID equals b.BrandID
                      join c in entities.CK_Stock
                      on a.ModelID equals c.ModelID
                      select new DetailsItemType
                      {
                          Model= a,
                          Brand = b,
                          Stock = c
                      };
        return details.ToList();
    }
}

现在每次调用GetDetails()时,你都可以访问这3张表。比如说

var details = GetDetails();
var model = details.Model;
var brand = details.Brand;
var stock = details.Brand;
© www.soinside.com 2019 - 2024. All rights reserved.