[英]Entity Framework classes, extending EF classes and adding custom properties, iQueryable and Get method
我对如何命名这个名称不知所措,因此,如果有人可以更适当地重命名它,将不胜感激。
我对如何填充部分实体类的自定义属性感到困惑。 一些例子
// 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))填充一个新的List。
在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));
似乎有点脏...
好吧,您可以消除n + 1个选择:
public List<Comment> IQueryable2ToList(IQueryable<Comment> comments)
{
List<Comment> comments = comments.ToList()
foreach (Comment c in comments) {
c.UpVotes = 0 //get UpVotes
c.DownVotes = 0 // get DownVotes
}
return comments;
}
但是,那不是我要做的。 相反,我将创建一个演示模型和项目:
public class CommentPresentation {
public int CommentID { get; set; }
public string WittyInsight { get; set; }
public int UpVotes { get; set; }
public int DownVotes { get; set; }
public int CurrentVotes()
{
return UpVotes - DownVotes;
}
}
public IQueryable<CommentPresentation> ToPresentation(IQueryable<Comment> comments)
{
return from c in comments
select new CommentPresentation
{
CommentId = c.CommentId,
WittyInsight = c.WittyInsight,
UpVotes = 0,
DownVotes = 0
};
}
如果要分配常量以外的其他内容,则可能必须经过AsEnumerable()
,因此您要先进行分页。 但这应该可以帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.