开发者

LINQ to ADO.net Entities

this is the first time i use entities, I usually use stored procedures. I'm using Ado.net Entities and on the db I ve got folders tabl开发者_Go百科e with id,name and bookmarks table with folderid,name,url

I can get folder names with

protected IEnumerable<folder> GetFolderList()
{
    using (DBEntities db = new DBEntities())
    {
        var folderList = from f in db.folders where f.userId == userid select f;
        return folderList.ToList();
    }
}

and print it with

    <%foreach (BookmarksDBModel.folder f in folderList){%>
    <option value="<%=f.id %>"><%=f.name %></option>
    <%}%>

I wanted to get number of bookmarks in each folder so I wrote

var folderList = from f in db.folders
                    where f.userId == userid
                    select new
                    {
                       linkcount = (from b in db.bookmarks where b.folderId == f.id select b).Count(),
                       f.name,
                       f.id
                    };

problem is folders class doesn't have property called linkcount. What do i need to do get linkcount? Do I need to add another property to folders class?


In your query, you're actually returning an anonymous type, so you could write:

var folderList = from f in db.folders
                where f.userId == userid
                select new
                {
                   linkcount = (from b in db.bookmarks where b.folderId == f.id select b).Count(),
                   folder = f
                };

And you can access the information with:

foreach(var folderResult in folderList)
{
  Console.WriteLine("FolderId: " + folderResult.folder.id + ", Count: " + folderResult.linkcount);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜