是否可以在域对象上使用属性和IValidatableObject?

时间:2015-09-23 14:48:50

标签: asp.net-mvc domain-driven-design

我习惯使用实体对象,现在我正在切换到DDD原则,所以我将开始使用域对象。

我习惯使用RequiredAttributeStringLengthAttribute等属性来装饰我的实体对象的属性。我也习惯在我的实体对象上实现IValidatableObject

我的问题是 - 在我的域对象上使用属性和IValidatableObject是否可以接受?它与DDD一致吗?谢谢。

2 个答案:

答案 0 :(得分:2)

您的域模型应仅适用于业务概念,不应与DAL或View有任何直接关系。您已应用的属性意味着您将域模型用作视图模型。创建单独的viewmodel。不要将描述存储模型的实体对象用作域的根类。为域对象创建新类。添加明确解释业务的方法 -

ChangeLastName(string newName)代替obj.LastName = "Some name"

CreateNewPost(string text,string author)代替obj.Posts.Add(..)

你可以编写一些扩展方法来制作映射,比如ToViewModel,或者做其他一些。一个有趣的设计/基础设施模式是CQRS& EventSourcing。它允许您避免映射,但有一些缺点(如聚合之间的事务)。最后 - 在大多数情况下,简单的CRUD操作更适合 - 快速,简单,容易。

答案 1 :(得分:0)

从DDD的角度来看,最好在实体的行为方法中使用例外或通过实施 Specification Notification 模式以强制执行验证规则。

在应用程序层的<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res /android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000" tools:context=".MainActivity"> <LinearLayout android:id="@+id/fragmentContainer" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:orientation="horizontal" /> </androidx.constraintlayout.widget.ConstraintLayout> 类(而不是域实体)中使用数据注释来接受输入是有意义的,以允许在UI层中进行模型验证。但是,不应在域模型中排除验证的情况下完成此操作。

相关问题