I have a class, NewsItem, and I would like to create a list of child objects IList using entity framework and lazy loading.
My NewsItem class is straight forward:
public class NewsItem { public int ID { get; set; } public DateTime PublicationDate { get; set; } public DateTime LastUpdated { get; set; } public int? TopPictureID { get; set; } public virtual Picture TopPicture{get; set;} public string Headline { get; set; } public string StandFirst { get; set; } public string Body { get; set; } public IList<DirectComment> Comments { get; set; } } The comments class is based upon a table that can have comments for other article types (e.g. PR, blogs, features) as well as NewsItems:
public class DirectComment { public int ID { get; set; } public DateTime Published { get; set; } public string Comment { get; set; } public bool Live { get; set; } public int ArticleID { get; set; } public string ArticleType { get; set; } } I am unsure as to how I would get all comments for a news item, where I would have a Where statement that specifies the DirectComment.ArticleType as "newsitem" and ArticleID of, for example, 1000 - that will lazy load and also will not create an issue for Dependency injection.
I could just put something akin to the following in the NewsItem.Comments Get statement:
public class NewsItem { [...] [NotMapped] private IList<DirectComment> comments; [NotMapped] public IList<DirectComment> Comments { get { if (null == comments) { IDirectCommentRepository dcRepository = new DirectCommentRepository(); comments = dcRepository.DirectComments.Where(dc => dc.ArticleID == this.ID && dc.ArticleType == "news").ToList(); } return comments; } } } ...however, that wouldn't be great for DI as it means that I will have to hard-code the "New DirectCommentRepository()" and it will be an issue when it comes to Unit Testing. So, is it possible for me to get around the problem?