【发布时间】:2011-02-16 17:10:34
【问题描述】:
我不知道如何命名它,所以如果有人可以更恰当地重命名它,那将不胜感激。
我不知道如何去填充部分实体类的自定义属性。一些例子
// partial class from EF base class - base class contains
// properties such as commentID, comment, userID etc
// Comments.cs
public partial class Comment {
public int UpVotes { get; set; }
public int DownVotes { get; set; }
public int CurrentVotes()
{
return UpVotes - DownVotes;
}
}
_
//CommentRepository.cs
//snip
public Comment GetItem(int id)
{
Comment c = db.Comments.SingleOrDefault(x => x.CommentID == id);
c.UpVotes = 0 //get UpVotes
c.DownVotes = 0 // get DownVotes
return c;
}
public IQueryable<Comment> GetAllCommentsByPage(int pageid)
{
}
public IQueryable<Comment> GetAllCommentsByPage(string slug)
{
}
public IQueryable<Comment> GetCommentSelection(int PageID, int Skip, int Take)
{
}
public int CountCommentByPage(int PageID)
{
}
在旧的 .Net 1.x 时代,我会让 GetAllx 方法选择一个 CommentID 列表,然后使用 List.Add(GetItem(ID)) 填充一个新列表。
在 EF4 中,我想做类似的事情,但不会错过 IQueryables 的延迟执行。
在一些情况下,我发现在执行最终的 .ToList() 或类似方法以获取实际数据之前快速连续堆叠这些 GetAllx 方法很有用。
有没有一种明智的方法可以让我做我希望相当简单且逃避我的事情?我不希望必须更改每种方法以返回可以通过一个 GetItem 方法生成的静态项目列表。
提前致谢。
----- 编辑-----
好的,这是我目前的解决方案:
public List<Comment> IQueryable2ToList(IQueryable<Comment> c)
{
List<Comment> comments = new List<Comment>();
List<int> ids = c.Select(x => x.CommentID).ToList();
foreach (int id in ids) {
comments.Add(GetComment(id));
}
return comments;
}
我这样做:
List<Comment> comments = (new CommentRepository()).IQueryable2ToList(db.FindAllCommentsByPage(slug));
这似乎有点脏……
【问题讨论】:
-
您拥有的代码的哪一部分实际上不起作用?
-
抱歉,我可能没有说清楚。没有任何东西真正损坏。我只希望每个 IQuerable
选择都返回 GetItem 中列出的 cmets 列表(使用我的自定义额外参数),而不是 EF 将返回的库存参数。
标签: c# linq entity-framework asp.net-mvc-2