开发者

What's the most efficient way to inject behavior into all my entities?

I'm converting a large data model from an old Microsoft data access library to Entity Framework 4. I'd like to "inject" these two methods into most, if not all, of the entities that have been generated from the existing database into my EF model:

    public bool Deleted
    {
        get { return this.EntityState == System.Data.EntityState.Deleted; }
        set 
        {
            if (value)
                Context.DeleteObject(this);
        }
    }

    public b开发者_运维知识库ool Inserted
    {
        get { return this.EntityState == System.Data.EntityState.Added; }
        set
        {
            if (value)
                Context.AddObject(this.GetType().Name, this);
        }
    }

Rather than creating a partial class for each entity (there are over 100), what's the better way to add these methods to all the entities in the model?

Thanks in advance for your suggestions.


I'd modify the EF T4 template to generate these properties automatically.


Expanding on @Daz's (somewhat sparse) answer: Right-click in the designer and select Add Code Generation Item..., then ADO.NET Entity Object Generator. It will create a template that generates exactly the same code that the compiler already creates, which you can then customize. Open it up, it's pretty easy to see how to modify it. It's designed for exactly the purpose you describe.

Here's a recent MSDN article describing things in detail.


Create a new base class for your entities, it should inherit the current one you are using and extend its members with that code.


Extension methods do the trick. But of course they are methods, not proper properties like you make in your sample (extension properties don't exist yet in the framework, only extension methods).

public static class EntityObjectExtensions
{
    public static bool IsDeleted(this EntityObject obj)
    {
        return obj.EntityState == System.Data.EntityState.Deleted;
    }

    public static bool Delete(this EntityObject obj)
    {
        Context.DeleteObject(obj);
    }

    public static bool IsInserted(this EntityObject obj)
    {
        return obj.EntityState == System.Data.EntityState.Added;
    }

    public static bool Insert(this EntityObject obj)
    {
        Context.AddObject(obj.GetType().Name, obj);
    }
}

Undoubtly this solution is the most elegant and the nearest from your demand. No need to touch the code generation nor to duplicate the same code on all your classes. If something has to evolve in these methods, the changes will be done in one single place and all your classes will take benefit from it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜