Entity Framework 4.1 - Code first. Doesn't EF override my virtual members?

我与影子孤独终老i 提交于 2019-12-25 00:30:00

问题


I’m building a system using domain driven design and EF 4.1. In some of my properties I have logic preventing illegal values to be set and if so throwing an exception. I thought EF, when instantiating my classes, created a new temporary class e.g. MyClass_abc123… inheriting from MyClass that overrides all virtual members to be able to set them with data from the DB. When EF instantiates the class below and try to set the property MyObj the exception is being thrown. Anyone got a clue or a nice way to solve it?

public class MyClass
{
    private MyObject _myObj;
    public virtual MyObject MyObj
    {
        get { return _myObj; }
        set
        {
            if (!check some logic...)
                throw new Exception();

            _myObj = value;
        }
    }
}

BR Philip


回答1:


EF doesn't override your internal logic. EF only wraps it and wrapper properties still call base setter and getter.

Edit:

There is no build in way to avoid this. Simply you put some logic to your entities and you are responsible for it. The setter is called when loading entity from the database as well because it must set your properties. If you don't want your logic to execute when you load entity from the database you must add some other logic which will turn your validation on after the object is loaded. To turn your validation on you can handle:

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.ObjectMaterialized += YourHandler

In ObjectMaterialzied handler you need to check the type of materialized object and convert it to type exposing your TurnOn feature and simply call it.



来源:https://stackoverflow.com/questions/7007045/entity-framework-4-1-code-first-doesnt-ef-override-my-virtual-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!