简体   繁体   中英

Entity framework projection or

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?

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.

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