asp.net mvc - Generic save method -


in generic repository need write generic save method edit existed or add new entity depending on id.

public void save<t>(t entity) t : tentity, ikeyid {     if (objectset.any(r => (r ikeyid).keyid == entity.keyid))     {         edit(entity);     }     else     {         add(entity);     } } 

but linq generate exception when try any( r=> (r ikeyid).... the 'typeas' expression input of type 'myprog.dal.appeal' , check of type 'claimstrak.dal.interfaces.ikeyid' not supported. entity types , complex types supported in linq entities queries.

how write correct?

well, truth dont need use objectset, can use dbcontext this, in more easy way.

bu, tell not pattern use, call save() in repository. recomend consider .savesession() of context after done, way can lot of things befose making round trip te database.

so, should make method this, not call savechanges(), instead of save() method, updateorinsert() , them, after done call .save()

but give examplefollowing request (but dont recommend, recommend separate iunitofwork irepository)

see how code simple:

    interface ikeyid     {         int id { get; set; }     }      dbcontext context = new yourcontext();      public bool save<tentity>(tentity entity) tentity : class, ikeyid     {         return (entity.id == 0) ? add<tentity>(entity) : edit<tentity>(entity);     }      public bool edit<tentity>(tentity entity) tentity : class, ikeyid     {         var set = context.set<tentity>();         set.attach(entity);         return true;     }      public bool add<tentity>(tentity entity) tentity : class, ikeyid     {         var set = context.set<tentity>();         set.add(entity);         return true;     } 

i use similar approach im repositories, have changed t4 (.tt file) generates poco classes database excplicitly implement interfaces have, such iauditable, ivalidatable , other, t4 automaticaly implement interfaces in classes.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -