是否可以使用实体框架部分方法更新更改事件的值
我想知道如何在使用实体框架时更改输入值。到目前为止,我正在使用自制的自定义类,并将其转换为实体类。我想我要做的工作加倍了。在自定义类中,我在设置器处转换传入值。荷兰的邮政编码为 4 位数字加 2 个字符。有些人用空格将它们分开,有些人将它们连接在一起。此时,如有必要,正则表达式会将数字与字符分开。使用实体框架时。在将值写入数据库之前是否可以更改传入值?如果是这样我该怎么做?
我正在寻找验证,但我看到的所有示例都只抛出错误,而没有有效地转换值。
荷兰邮政编码示例:“5126HG”或“5126 HG”在数据库中应产生相同的结果。我已经知道如何改变,但不知道在哪里以及如何申请。
I was wondering how to change input values when using the Entity Framework. Till now I'm using selfmade custom classes which I transform to entity classes. I think I'm doubling the work i have to do. In the custom class I transform the incomming value at the setter. Postal codes in the netherlands are 4 digits plus 2 characters. Some people seperate them with a space, others join them together. At this moment a Regex wil seperate the digits from the characters if necessary. When using the Entity Framework. Is there a possibility to change the incomming value before writing the value to te database? And if so how do I do so?
I was searching for validation but all examples I saw where only throwing errors without effectively transforming the value.
Example of Dutch Postal Code: "5126HG" or "5126 HG" should both result in the same result in the database. I already know how to change, but not where and how to apply.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为使用自定义类是一个好主意,它类似于实现DTO模式,并且是将业务层与数据访问层分离的好方法。但是如果您想向实体类添加一些验证/修改方法,您可以这样做。
如果您使用的是 EF 4.1,则生成器将作为部分类创建实体的 POCO 类。您可以添加自定义分部类来添加验证方法,但您需要在执行数据库操作之前显式调用这些方法。
另一种方法是使用自定义 SaveChange 处理程序。您可以在此处找到 SaveChange 自定义的示例。
http://msdn.microsoft.com/en-us/library/cc716714.aspx
I think that using custom classes is a good idea, it's similat to implement the DTO pattern and it's a good method to separate business layer from data access layer. But if you want to add some validation / modification methods to the entity classes you can do it.
If you are using EF 4.1 you have POCO classes for entities createted by the generator as partial classes. You can add your custom partial classes adding validation methods, but you need to explicitly call these methods before executing a db operation.
Another way is using a custom SaveChange handler. Here you can find an example of SaveChange customization.
http://msdn.microsoft.com/en-us/library/cc716714.aspx
最好有一些单独的
Controller
类,其中的方法可以接受、验证、转换输入,然后仅使用有效、正确且一致的值设置Entity
属性。这样,您的实体始终有效且正确,并且在写入数据库之前您永远不需要非标准机制来更改值。
It is better to have some separate
Controller
class with a method that takes, validates, transforms inputs and only then setsEntity
properties with valid, correct and consistent values.This way your
Entities
are always valid and correct and you never ever need a nonstandard mechanism to change values before writing to the database.