当把功能和验证code实体框架 [英] Where to put functions and validation code Entity framework

查看:173
本文介绍了当把功能和验证code实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪里和如何(code的例子将是巨大的),我可以从自动生成的类例如Customer.cs删除在我Model.edmx业务逻辑

Where and how (code example would be great) can I remove business logic from auto generated class for example Customer.cs under my Model.edmx

当我编辑的东西在设计,然后保存改变EF更新类,所以我需要例如默认值进入(我知道我可以将它们设置在设计师)了。

When I edit something in the designer and then save that changes EF update class so I need to enter for example default values (I know I can set them in designer) again.

public Customer()
{
    this.Blocked = false;
    this.Code = "#00000";
    this.Contacts = new ObservableListSource<Contact>();
}

另外如何创建/在哪里把一些基本的验证(这一点。code不能为空字符串或空)?

Also how to create/where to put some basic validation (this.Code cannot be empty string or null) ?

感谢。

推荐答案

类由实体框架生成的标记部分关键字,您可以扩展它们添加新的文件和创建部分类的其他部分。这也prevent更改的,当你更新模型被覆盖。

Classes generated by Entity Framework are marked with partial keyword and you can extend them adding new file and creating other part of the partial class. This also prevent your changes from being overwritten when you update the model.

也许什么更重要的是,EF增加了设置的部分方法,每一个对应的属性,它允许您添加自己的验证逻辑:

And maybe what even more important, EF adds set of partial methods to every mapped property, which allows you to add your own validation logic:

属性 修改 - 包括code中的变化发生之前执行,如属性验证。该值的参数是   值该属性正在发生变化。实现此方法   发生之前就确认属性更改。为prevent变化   被制成,必须抛出异常。

OnPropertyChanging - include code to execute before the change occurs, such as property validation. The value parameter is the value to which the property is changing. Implement this method to validate a property change before it occurs. To prevent the change from being made, you must throw an exception.

属性 更改 - 包括code修改发生后,如登录的变化来执行

OnPropertyChanged - include code to execute after the change occurs, such as logging the change.

如何:执行业务逻辑在标量属性更改

您分部类应该看起来像:

Your partial class should look like that:

public partial class Customer()
{
    partial void OnCodeChanging(string value) 
    {
        if(string.IsNullOrEmpty(value))
            throw new InvalidOperationException ("value cannot be null or empty");
    }

}

您必须确保它存在于同一个命名空间的另一部分,由EF创建。

You have to make sure it exists in the same namespace as the other part, created by EF.

这篇关于当把功能和验证code实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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