我与MVVM一起使用实体框架。 我的层是这样的:实体从数据库直接链接到viewModel - 不好的做法?
- 查看
- 视图模型:提供数据和视图命令。
- 服务:提供对DAL的访问。包含业务逻辑。
- DAL:提供对数据库的访问。我将库模式与UnitOfWork一起使用。
我的ViewModel中的属性或多或少直接绑定到我的数据库中的实体。例如:
public class MyViewModel
{
private MyEntity _myEntity;
private MyService _myService;
// A property which is bound to my view (bidirectionally)
public string TextToDisplay
{
get { return _myEntity.SomeText; }
set
{
if (_myEntity.SomeText != value)
{
_myEntity.SomeText = value;
RaisePropertyChanged("TextToDisplay");
}
}
}
// Method called by a command when the "Save"-button is pressed
private void Save()
{
_myService.Save(_myEntity);
}
}
public class MyService
{
private MyRepository _myRepository;
private IUnitOfWork _unitOfWork;
public void Save(MyEntity myEntity)
{
_myRepository.Insert(myEntity);
_unitOfWork.Save();
}
}
所以当Save
被呼叫时,数据库生成的属性/特性(如ID
)被更新/自动生成。
这是否会导致副作用?这是不好的做法吗?
你如何处理它?将数据从数据库传递给视图模型时,是否“分离”或复制对象?或者,传递给视图模型的对象甚至应该是另一种类型?我怎样才能完美地处理这件事?