Entity Framework return value of custom Query methods
I'm new to EF and MVC, so as a training i'm working on something like "BlogEngine". I use repository pattern and T4 in my project etc. as normal methods that return single Entity or list of an entity (List) i have no problem, but my question is in cases that i want my repository or service layer classes, return custom queries or views(sql).
Lets imagine i want to show list of all categories including PostCount of each category, or list of all post including CommentCount and some other custom fields. I dont know i must create new classes that has these extra fields or what, (what if i have lots of different views in my project, is this neat?)
I myself came up with methods whit "dynamic" return values.
public dynamic GetAllPostsWithRelatedData()
{
return (from post in (postRepository.GetAll() as ObjectQuery<Post>)
开发者_如何学编程 //.Include("Categories").Include("Tags")
select new
{
Categories = post.Categories,
Tags = post.Tags,
CommentsCount = post.Comments.Count,
post.User.UserName,
post.Content,
post.LastModified,
post.Slug,
post.Title
});
}
any better ideas?
Imo better idea is to use custom type for projections or return IQueryable<Post>
from your repository and let upper layer to define a query and use annonymous type directly.
dynamic
keyword should be used when it is useful to have dynamic behavior with resolving at runtime. This is not the case. You know exactly what type you want to return from your method.
If you want to define custom views which will be used often you can define them in SQL as well and map them as new entity (you have better control over SQL). You can also use advanced features of EF like DefiningQuery or QueryView which also result in new entity in your model.
精彩评论