如何在 Microsoft MVC2 中自动生成的实体上实现业务逻辑?
我是 MVC 新手,我正在尝试弄清楚如何在 MVC 项目中自动生成的实体中实现业务逻辑。
我知道,如果我创建自己的 Model 类,我可以将 [Required]
和其他属性放在字段上,但在 .edmx 文件中似乎没有选项可以执行此操作。
我在这里缺少什么吗?
我应该创建自己的使用实体并将逻辑放入其中的类吗? 看来应该有一个办法可以让我少做点工作。
谢谢!
I'm new to MVC and I'm trying to figure out how to implement business logic in the auto generated Entities in an MVC project.
I know that if I create my own Model class I can put [Required]
and other attributes on the fields but there doesn't seem to be an option to do that in the .edmx file.
Is there something I'm missing here?
Should I be creating my own classes that use the entities and put the logic in there?
It seems like there should be a way for me to do less work.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以通过使用 .NET 中专门为此原因实现的伙伴类功能来实现。在 .ebmx 文件中创建实体后,您可以创建伴随实体的部分类,这些实体在“伙伴类”中定义业务规则。
在上面的示例中,假设您已在对象上下文中定义了“产品”类型,该类型具有“名称”、“价格”和“描述”属性。只要 MetadataTypeAttribute 引用的好友类类型即可 具有匹配的属性名称,应用于伙伴类中的属性的属性将应用于实现类型。
注意:如果伙伴类中有任何属性名称与实现类型不匹配,您将收到运行时错误。您只需在伙伴类中为您有兴趣应用业务规则的属性创建匹配的属性即可;所有属性都是可选的。
This can be achieved by using the buddy-class functionality in .NET implemented specifically for this reason. Once you have created your entities in your .ebmx file you can create partial classes to accompany your entities which define your business rules in a 'buddy class'.
In the example above, assume that you already have a "Product" type defined in your object context which has properties for "Name", "Price", and "Description". So long as the buddy class type referenced by the MetadataTypeAttribute has matching property names, the attributes applied to the properties in the buddy class will be applied to the implementation type.
Note: if there are any property names in the buddy class which do not match the implementation type, you will get a runtime error. You only need to create matching properties in the buddy class for the properties you are interested in applying business rules to; all properties are optional.