我與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
)被更新/自動生成。
這是否會導致副作用?這是不好的做法嗎?
你如何處理它?將數據從數據庫傳遞給視圖模型時,是否「分離」或複製對象?或者,傳遞給視圖模型的對象甚至應該是另一種類型?我怎樣才能完美地處理這件事?