问题
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