0

Let's say I have existing application with Db which was designed using EF Model First approach. I have Users table, when client-code tries to read an entry from Users table DAL logic projects EF entities to plain objects (which are just simple C# classes, let's call it UserEntry class).

Right now I should add Update method, which takes UserEntry class. So I am just wondering how should I track what fields were changed in UserEntry class?

Sure I can save all data, but I don't what such approach.

I can completely re-factor the existing solution, I can even remove UserEntry classes. What approach should I choose? Generate POCO classes using DbContext generator or for example use EF Power Tools and move to the Code First approach?

Jevgenij Nekrasov
  • 2,690
  • 3
  • 30
  • 51
  • Why not let Entity Framework deal with that? That's the whole point with the EF Code First ORM abstraction. – Tejs May 04 '12 at 15:43
  • Read about self tracking entities in EF –  May 04 '12 at 15:48
  • @Tejs I want clean and simple classes, which I can easily manipulate and no performance issues (http://stackoverflow.com/questions/7587232/entity-framework-projection-into-class-is-faster-than-selecting-ef-poco-objects). So are you suggesting to use CF? In this case I should reverse my database back – Jevgenij Nekrasov May 04 '12 at 15:48
  • 2
    If you want pure performance, then you should probably stick with plain old ADO.NET and Stored Procedures. ORMs can be fast, but they arent going to be the fastest things around. The point of using the ORM is to abstract all the database change tracking and manipulation from the code. EF Code First can figure out what properties changed when you call to Insert or save changes. – Tejs May 04 '12 at 15:50
  • http://msdn.microsoft.com/en-us/library/ff407090.aspx –  May 04 '12 at 15:52

1 Answers1

0

I don't know what version of EF are you using, so I'll assume you have DbContext at your disposal, in some way like this:

public class YourContext : DbContext
{
    public DbSet<User> Users {get;set;}
}

First you load your user with method like this, so that DbContext tracks it:

YourContext db = new YourContext();

public User Get(int userId)
{
    return db.Users.Find(userId);
}

Now it is in the memory, and you operate over object that was returned. When you're done meddling with it, you just call:

db.SaveChanges() 

and it will save whatever was tracked as changed, no need for special Update method.

If however you're working with disconnected entities (websites and such), you need to add additional line that will tell DbContext that entity was changed when it was out of scope of tracking:

public void Update(User user)
{
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

That's pretty much all you need.

Admir Tuzović
  • 10,997
  • 7
  • 35
  • 71