我应该返回哪种类型?

时间:2016-12-05 15:18:59

标签: c# linq

这里我有两个包含一些列的表。我的目标是我想使用ChilsMaster进行GroupBy操作

public partial class Master
{
    public int MasterId { get; set; }
    public string Prod_Name { get; set; }
    public string Produ_Adress { get; set; }
    public Nullable<decimal> Price { get; set; }
}

public partial class ChildMasterMaster
{
    public int ChildId { get; set; }
    public Nullable<int> MasterId { get; set; }
    public string SalesRec { get; set; }
    public Nullable<bool> Prod_Deliver { get; set; }
}

public class Market_Masters
{    
    public int MasterId { get; set; }
    public string Prod_Name { get; set; }
    public string Produ_Adress { get; set; }
    public Nullable<decimal> Price { get; set; }
    public int ChildId { get; set; }
    public string SalesRec { get; set; }
    public Nullable<bool> Prod_Deliver { get; set; }
}

在这里,我使用此连接编写一个私有文件,其中包含表的两列:

 public IEnumerable<Market_Masters> GetMaster()
 {
     var x = from n in db.Masters
             join chil in db.ChildMasterMasters on n.MasterId equals chil.MasterId into t
             select new
             {
                 n.MasterId,
                 n.Prod_Name,
                 n.Produ_Adress,
                 n.Price,
                 Hello = t
             };
    return ???;
}

如果我写.ToList()它会抛出异常

1 个答案:

答案 0 :(得分:0)

您无法从方法(即select new { ... })返回匿名类型。您需要为其创建一个类,或者如果它属于该类型,则使用Market_Masters,例如:

public IEnumerable<Market_Masters> GetMaster()
{
    var x = from n in db.Masters
            join chil in db.ChildMasterMasters on n.MasterId equals chil.MasterId into t
            select new Market_Masters()
                {
                    MasterId = n.MasterId,
                    Prod_Name = n.Prod_Name,
                    Produ_Adress = n.Produ_Adress,
                    Price = n.Price,
                    Hello = t
                };

    return x.ToList();
}

如果返回的类型不是Market_Masters,您可以执行类似的操作(将YourChildType替换为您的实际类型):

public class MarketMastersWithHello : Market_Masters
{
    public IEnumerable<YourChildType> Hello { get; set; }
}

然后:

public IEnumerable<MarketMastersWithHello> GetMaster()
{
    var x = from n in db.Masters
            join chil in db.ChildMasterMasters on n.MasterId equals chil.MasterId into t
            select new MarketMastersWithHello()
                {
                    MasterId = n.MasterId,
                    Prod_Name = n.Prod_Name,
                    Produ_Adress = n.Produ_Adress,
                    Price = n.Price,
                    Hello = t
                };

    return x.ToList();
}