entity framework - How to create generic EF Insert method? -


i'd create generic c# class method add row database using entity framework.

i have 1 table called address. i've written following code add address database:

public class addressexchange {     public int insert(address address)     {         using (var db = new demowebentities())         {             //db.addobject("address", address);             db.addresses.addobject(address);             db.savechanges();             return address.id;         }     } } 

i write generic class perform operation any entity in edmx. think should this:

public class entityexchange<t, keytype> {     public keytype insert(t t)     {         using (var db = new demowebentities())         {             // entity set name might wrong.             db.addobject(typeof(t).name, t);                              // ef doesn't know primary key is.             return t.id;         }     } } 

i think may possible use addobject method add object database, entityset name not same type name, if has been pluralized!

i want return primary key caller, don't know how tell field contains primary key.

i have generic insertorupdate method in generic repository ensures proxies created. (proxies required support lazy loading , if create entity using "new", proxies not created). see question here

public class repositorybase<t> : irepository<t> t : modelbase {     public virtual t insertorupdate(t e)     {         dbset<t> dbset = context.set<t>();          //generate proxy type support lazy loading         t instance = dbset.create();          dbentityentry<t> entry;         if (e.gettype().equals(instance.gettype()))         {             //the entity being added proxy type              //supports lazy loading context entry             entry = context.entry(e);         }         else         {             //the entity being added has been created using "new" operator.              //attach proxy             //need set id before attaching or              //the property 'id' part of object's key              //information , cannot modified when call setvalues             instance.id = e.id;             entry = context.entry(instance);             dbset.attach(instance);              //and set it's values of entity             entry.currentvalues.setvalues(e);             e = instance;         }          entry.state = e.id == default(int) ?                                 entitystate.added :                                 entitystate.modified;          return e;     } }  public abstract class modelbase {     public int id { get; set; } } 

note models inherit modelbase handles id issue , return entity rather id. not strictly necessary since reference entity passed in , ef performs fixup on id anyway can access refernce passed in.


Comments