实体框架4.1 - 代码优先。 EF不会覆盖我的虚拟成员? [英] Entity Framework 4.1 - Code first. Doesn't EF override my virtual members?

查看:410
本文介绍了实体框架4.1 - 代码优先。 EF不会覆盖我的虚拟成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用域驱动设计和EF 4.1构建系统。在我的一些属性中,我有逻辑防止非法值被设置,如果是这样抛出异常。我认为EF,当实例化我的类,创建一个新的临时类,例如。 MyClass_abc123 ...继承自MyClass,它覆盖所有虚拟成员,以便能够使用数据库中的数据设置它们。当EF实例化下面的类,并尝试设置属性MyObj抛出异常。任何人都有一个线索或一个很好的方法来解决它?

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

推荐答案

EF不会覆盖您的内部逻辑。 EF只包装它和wrapper属性仍然调用基本setter和getter。

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

编辑:

没有构建方式来避免这种情况。简单地,你把一些逻辑,你的实体,你负责。从数据库加载实体时,也会调用setter,因为它必须设置属性。如果您不希望在从数据库加载实体时执行逻辑,则必须添加一些其他逻辑,这将在加载对象后打开验证。要打开你的验证你可以处理:

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

ObjectMaterialzied 处理程序你需要检查物化对象的类型,并将其转换为暴露您的TurnOn功能的类型,并简单地调用它。

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.

这篇关于实体框架4.1 - 代码优先。 EF不会覆盖我的虚拟成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆