简体   繁体   中英

How do you use SaveChanges() method in Ado.net Entity Framework?

I set up an IDataContext and when i create a data class for an entity, i inherit it from IDataContext.

IDataContext interface has 4 methods.

IQueryable<T> GetAll();
T GetById(long id);
void Add(T entity);
void Delete(T entity);
void Save(T entity);

As you know Delete and Save methods have this structure;

FooEntities db = new FooEntities();

db.DeleteObject(Foo entity);
// or save changes method
db.SaveChanges();

I meant these two methods could be generalized or something...

My question is how and where do you use these two methods.

  • Inside of the each data class for an entity
  • or another way of using.

You can abstract away the details of the framework with the Repository pattern. Here is an example implementation of IRepository for the Entity Framework. As for where to invoke the actual deleting and saving, your Controller/Presenter is a likely candidate.

DeleteObject is used to delete an object from the store. Calling DeleteObject as you have above marks the object as deleted. The call to SaveChanges() actually commits that change to the database. Both are necessary to delete an object from the store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM