开发者

How can I execute code when an entity is being persisted to the database with Entity-Framework code-first?

Is there a ni开发者_开发百科ce way to execute code when an entity is being saved to the database using EF/code-first?

I have a Url property on many of my entities. If a URL has not been given explicitly, I would like to calculate one as the object is persisted, eg.:

public void OnModelSaving()
{
    // If a URL has not been specified, generate one from the name.
    if (this.Url == null)
    {
        this.Url = Helper.GenerateSafeUrl(this.Title);
    }
}

Ideally, I'd like all this code to be stored inside the Model, but since I don't have an EF-owned base/partial class, I suspect if it's possible, I'd have to register/wire it up elsewhere. Question is - is it possible, and if so, how do I wire it up?


The only way is to override SaveChanges method on your context, iterate through changed entities and check the Url

public override int SaveChanges()
{
    var entities = ChangeTracker.Entries()
                                .Where(e => e.State == EntityState.Added || 
                                            e.State == EntityState.Modified)
                                .Select(e => e.Entity())
                                .OfType<YourEntityType();

    foreach (var entity in entities)
    {
        entity.Url = ...;
    }

    return base.SaveChanges();
}

If you have many entity types providing Url you can try to define interface with that Url implemented by all that entity types and in OfType use that interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜