隨着Caliburn.Micro我想知道暴露EF4實體作爲ViewModel屬性的優點和缺點(一種技術討論hereand here)。這使我可以避免爲每個字段寫入getter和setter(請參閱下面的OneCustomer)。缺點是我需要在XAML中編寫所有綁定語句(在LastName不在ViewModel中,但確實需要XAML綁定)。如果我堅持使用每個字段的屬性填充ViewModel的規定技巧(如下面的FirstName),我最終必須編寫大量額外的代碼才能調用NotifyOfProperyChange。該應用程序將會非常大。 我應該公開每個實體作爲ViewModel的屬性嗎?綁定EF4與Caliburn.Micro:我應該公開我的實體作爲ViewModel的屬性?
在我的視圖模型:
private MyEntities _context = new MyEntities();
private BindableCollection<Customer> _custBindableCollection;
private Customer _oneCustomer;
private string _firstName;
public void Load()
{
_custBindableCollection = new BindableCollection<Customer>(_context.Customers.Where(row => row.CustomerType == "FOO"));
AllCustomers = _custBindableCollection;
_oneCustomer = _custBindableCollection.FirstOrDefault();
FirstName = _oneCustomer.FirstName;
OneCustomer = _oneCustomer;
}
public BindableCollection<Customer> AllCustomers
{
get { return _custBindableCollection;}
set {_custBindableCollection = value;
NotifyOfPropertyChange(() => AllCustomers);}
}
public Customer OneCustomer
{
get { return _oneCustomer;}
set { _oneCustomer = value;
NotifyOfPropertyChange(() => OneCustomer);}
}
public string FirstName
{
get { return _firstName; }
set {
_firstName = value;
_oneCustomer.FirstName = value;
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => CanSaveChanges);
}
}
public void SaveChanges()
{ _context.SaveChanges(); }
public bool CanSaveChanges { get { return IsValid; } }
筆者認爲:
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="First Name:" />
<TextBox x:Name="FirstName" />
</StackPanel>
<StackPanel Orientation="Horizontal" DataContext="{Binding Path=OneCustomer}">
<Label Content="Last Name:" />
<TextBox x:Name="LastName" Text="{Binding LastName}" />
</StackPanel>
<Button Content="Load Data" x:Name="Load" />
<Button Content="Save" x:Name="SaveChanges" />
<DataGrid x:Name="AllCustomers" />
在此先感謝。
這是很棒的信息。特別是CM會議將下劃線解釋爲點符號。我一定會檢查出AutoMapper和MVC書籍。一個小問題,雖然...應該實體屬性更新在setters(值),或者我應該等到保存點擊並一次全部更新?再次感謝。 – DeveloperDan
你問的是什麼時候堅持數據庫,當一個屬性值改變與用戶點擊保存? –
不,我會堅持保存(矮胖不健談的規則)。我在想的是,如果我不公開這個實體,我可以等到Save來更新所有的實體屬性。但現在我認爲這是沒有道理的,因爲即使只有一個值被更改,我也必須更新所有值。所以,我已經回答了我自己的問題 - 我會保留setter中的實體屬性/字段更新。 – DeveloperDan