Entity Models
Assuming we have entity models:
public class Post
{
public Post() { Tags = new List<Tag>(); }
public int Id{ get; set; }
public string Title{ get; set; }
public string ShortDescription{ get; set; }
public string Description{ get; set; }
public string Meta{ get; set; }
public string UrlSlug{ get; set; }
public bool Published{ get; set; }
public DateTime PostedOn{ get; set; }
public DateTime? Modified{ get; set; }
public int CategoryId { get; set; }
public virtual Category Category{ get; set; }
public virtual IList<Tag> Tags{ get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
public string Description { get; set; }
public virtual IList<Post> Posts { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
public string Description { get; set; }
public virtual IList<Post> Posts { get; set; }
}
Context
Our context class is pretty simple. The constructor takes the name of the connection string in web.configand we define three DbSets:
public class BlogContext : DbContext
{
public BlogContext() : base("BlogContextConnectionStringName") { }
public DbSet<Category> Categories { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Repository
:
public interface IBlogRepository
{
IEnumerable<Post> Posts(int pageNo, int pageSize);
int TotalPosts();
}
-, !
public class BlogRepository : IBlogRepository
{
private readonly BlogContext _blogContext;
public BlogRepository(BlogContext blogContext)
{
_blogContext = blogContext;
}
public IEnumerable<Post> Posts(int pageNo, int pageSize)
{
var query = _blogContext.Posts
.Where(p => p.Published)
.OrderByDescending(p => p.PostedOn)
.Skip(pageNo * pageSize)
.Take(pageSize)
.Include(b => b.Category);
return query;
}
public int TotalPosts()
{
return _blogContext.Posts.Where(p => p.Published).Count();
}
}
, , , web.config , ? , !
var context = new BlogContext();
var repository = new BlogRepository(context);
var posts = repository.Posts(0, 10);
:
foreach(var blog in blogs)
{
Console.WriteLine("Blog Id {0} was posted on {1} and has {2} categories", blog.Id, blog.PostedOn, blog.Categories.Count());
}
FetchMany/ToFuture, .