【问题标题】:mvc3 best way to convert anonymous type to an ienumerablemvc3 将匿名类型转换为可枚举的最佳方法
【发布时间】:2014-03-29 18:36:54
【问题描述】:

我有一个模型,它使用 IEnumerable 在视图中使用 foreach 语句返回多行。问题是我正在使用 Join 因为我需要来自 2 个不同表的数据,这会将 ienumerable 转换为匿名类型并导致错误;我可以解决这个问题的最佳方法是什么?

 var Ieposts = (from t in db.Threadposts join p in db.profiles on t.profileID equals p.profileID  where t.threadID == id  select new
                    {
                       firstname = p.firstname,
                        lastname = p.lastname,
                        articles = p.articlecount,
                       city = p.city,
                       state = p.state,
                       post = t.post
                    }).ToList();

我只取出我需要的字段,因为这会提高数据库性能。任何建议都会很棒

【问题讨论】:

  • 创建匿名类型的不是连接。这是“选择新”部分。

标签: asp.net-mvc-3 ienumerable anonymous-types


【解决方案1】:

我认为您确实需要更多地了解 Entity Framework 和 Linq。

联接不会创建匿名类型,从匿名类型获取可枚举也没有任何问题。只需从查询中调用 .AsEnumerable()。

但是,我怀疑这不是您想要做的。你真正想要的是一个具体的返回类型。在这种情况下,您可能希望为此创建一个类型:

public class IEPost {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int Articles {get;set;}
    public string City {get;set;} 
    public string State {get;set:}
    public Post Post {get;set;}
}

然后您像这样创建查询(注意“新 IEPost”部分):

var Ieposts = (from t in db.Threadposts 
               join p in db.profiles on t.profileID equals p.profileID
               where t.threadID == id  select new IEPost
               {
                   FirstName = p.firstname,
                   LastName = p.lastname,
                   Articles = p.articlecount,
                   City = p.city,
                   State = p.state,
                   Post = t.post
                }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2023-02-21
    • 1970-01-01
    • 2010-12-21
    • 2019-06-09
    相关资源
    最近更新 更多