[英]WPF MVVM Entity Framework Layering
我有這個架構:
------(WPF應用程序)(XAML,ViewModels)(知道業務邏輯但不知道DAL)
------(類庫)(業務邏輯)(知道DAL)
------(類庫)(DAL-實體框架(模型優先))(未引用任何人)
我的問題是我的DAL不知道任何業務邏輯類,因此在DAL中,如果我得到一個說例如Person的列表,則返回IEnumerable。 例如:
public static IEnumerable GetPersons()
{
using(StaffEntities context = new StaffEntities())
{
return context.Persons.ToList();
}
}
因此,當我從業務邏輯層獲得結果時,我對每個實體都有一個類對應物,對於DAL中的“人實體”來說,我在業務邏輯層中有clsPerson。 但是我的視圖模型對DAL並不了解,它只知道業務邏輯類,因此只知道clsPerson,因此我在業務邏輯中的代碼變成了
例如:
public static IEnumerable GetclsPersons()
{ return DAL.GetPersons(); }
我的大問題是,每當我得到某物清單時,必須保存或刪除某物,我必須在ViewModel中使用反射
因此,如果我的xaml具有綁定的clsPerson屬性:
public IEnumerable clsPersons { get; set; }
public ListCollectionView clsPersonList { get; set; }
clsPersons = BLL.GetclsPersons();
clsPersonList = new ListCollectionView((IList)clsPersons);
public clsPerson CurrentclsPerson { get; set; }
每次我為“ CurrentclsPerson”分配值時,我都必須使用反射
CurrentclsPerson.Firstname = clsPersonList.CurrentItem.GetType().GetProperty("Firstname")
.GetValue(clsPersonList.CurrentItem,null).ToString();
我希望不要在視圖模型中使用反射,而是考慮將業務邏輯和DAL放在一個類庫中,這樣就不必使用IEnumerable
你們用什么?
反正有避免這種情況嗎?
有沒有辦法解決?
請幫助..謝謝。
一種解決方案是將模型對象放在一個dll中,並在各處引用該對象。 如果您將所有邏輯都保留在模型對象之外,這將很容易且足夠好。
另一方面,您可能想在GUI中使用綁定,因此您需要對象來實現某些接口(例如INotifyPropertyChanged)。 您仍然可以有兩個單獨的實體分支,並使用映射在它們之間進行轉換。 Automapper是可以幫助您解決此問題的一種工具。
我正在使用T4模板將ToDto和ToEntity方法添加到類中以在它們之間進行轉換。
我會在您的商務課程中執行以下操作:
public static IEnumerable GetPersons()
{
using(StaffEntities context = new StaffEntities())
{
return from person in context.Persons.ToList()
select new Person()
{
Firstname = person.Firstname
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.