Entity Framework Best Practices In Business Logic?

前端 未结 5 530
北恋
北恋 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:18

    In my experience this code is not good, because you lose the capacity to navigate relationships through navigation properties.

    public List  getArticles( ){  
        using (var db = new ArticleNetEntities())
        {
            articles = db.Articles.Where(something).ToList();
        }
    }
    

    Using this approach you can't use the following code because a.Members is always null( db context is close and cant get data automatically).

    var articles = Data.getArticles();
       foreach( var a in articles ) {
           if( a.Members.any(p=>p.Name=="miki") ) {
               ...
           }
           else {
               ...
           }
        }
    }
    

    Using only a global db context is a bad idea because you must use a delete changes function

    in a point of your application yo do this but don't save changes and close the window

    var article= globalcontext.getArticleByID(10);
    article.Approved=true;
    

    then in another point of application you make some operation and save

    //..... something
    globalcontext.saveChanges();
    

    in this case previous article approved property is set to modified by entity framework. When you save, approved is set true!!!

    Best approach for me is use 1 context per class You can pass context to another external method if you need

    class EditArticle {
    
        private DbEntities de;
        private currentAricle;
    
        public EditArticle() {
            de = new DbEntities; //inizialize on new istance
        }
    
        loadArticleToEdit(Articele a){
            // a is from another context 
            currentArticle= de.Article.Single(p=>p.IdArticle==a.IdArticle){
        }
    
        private saveChanges(){
            ...
            pe.saveChanges();
        }
    }
    

提交回复
热议问题