简体   繁体   中英

Detecting object creation in Entity Framework Code First

I'm using Entity Framework 4.1.

I have a class with an autogenerated Id field

 public class User
 {
    [Key]
    public int Id { get; set; }
 }

I want to create some matching directories on disk ( eg c:\\MyProgramFiles\\UserId ) for each user. To do this, I need to detect that the object has been saved by Entity Framework, and thus has an Id assigned which I can use in the file path.

I would prefer to hook this up so I don't have to write code like:

MyObjectContext.SaveChanges();
FileHelper.CreateUserDirectories(newUser.Id);

As that relies on users not being added by any other code paths. So, I'd prefer to hook into the Entity Framework events, so I can detect Users being created and create the matching directories on disk.

The problem is that I can only see a 'SavingChanges' event on the ObjectContext. As this gets called before the object has been saved, it is useless, as the object still does not have an Id.

Is what I want to do achievable , and if so how do I go about it?

Cheers!

Does the answer to the following question help? Entity Framework SaveChanges - Customize Behavior?

It refers to creating your own derived context and overriding the SaveChanges method so you can add custom logic before and after calling base.SaveChanges().

Credit to Ladislav Mrnka for the answer.

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