Entity Framework Best Practices In Business Logic?

前端 未结 5 522
北恋
北恋 2020-12-12 11:46

I am using the Entity framework for the first time, and would like to know if I am using in the best practice.

I have created a separate class in my business logic

5条回答
  •  醉梦人生
    2020-12-12 12:14

    I would have the ctx as a private variable within each class, then create a new instance of this each time and then dispose when finished.

    public class ArticleService
    {
        private ArticleEntities _ctx;
    
        public ArticleService()
        {
            _ctx = new ArticleEntities();
        }
    
        public IEnumerable
    GetLatestArticles(bool Authorised) { return _ctx.Articles.Where(x => x.IsApproved == Authorised).OrderBy(x => x.ArticleDate); } public IEnumerable
    GetArticlesByMember(int MemberId, bool Authorised) { return _ctx.Articles.Where(x => x.MemberID == MemberId && x.IsApproved == Authorised).OrderBy(x => x.ArticleDate); } public void Dispose() { _ctx.Dispose(); _ctx = null; } }

    Then when calling this.

    ArticleService articleService = new ArticleService();
    IEnumerable
    article = articleService.GetLatestArticles(true); articleService.Dispose(); // killing the connection

    This way you can also add/update other objects within the same context and call a save method which saves any changes to the db through the Entity.

提交回复
热议问题