コンテキストを使用して直接作業することをお勧めしますか?たとえば、顧客のデータベースがあり、ユーザーが名前で検索し、リストを表示し、そのリストを選択してから、その顧客のプロパティを編集できるとします。Entity FrameworkとWPFのベストプラクティス
お客様のリスト(POCOまたはCustomerViewModels
にマップされている)を取得してすぐにコンテキストを閉じるにはコンテキストを使用する必要があるようです。次に、ユーザーがリスト内のCustomerViewModels
のいずれかを選択すると、UIのカスタマープロパティセクションに値が設定されます。
次に名前、タイプ、ウェブサイトのアドレス、会社のサイズなどを変更できます。保存ボタンを押すと、新しいコンテキストを開き、CustomerViewModel
のIDを使用して顧客レコードを取得し、その特性。最後に、私はSaveChanges()
に電話し、文脈を閉じます。これはたくさんの仕事です。
私の質問は、それを開いたままのコンテキストで直接作業するのではなく、なぜですか?私は長い生涯のスコープで同じコンテキストを使用して読むことは非常に悪く、必然的に問題を引き起こすでしょう。私の前提は、アプリケーションを1人だけが使用する場合、私はコンテキストを開いてすべてを行うことができます。しかし、多くのユーザーがいる場合は、簡潔な作業単位を維持して、要求ごとにコンテキストを開閉する必要があります。
提案がありますか?ありがとう。
@PGallagher - 完全な答えをありがとう。
@Brice - あなたの入力も参考になります
しかし、@Manos D.の「冗長コードのコメント」コメントは少し気になります。例を見てみましょう。私は顧客をデータベースに保管しており、私の顧客のプロパティの1つはCommunicationMethodです。
[Flags]
public enum CommunicationMethod
{
None = 0,
Print = 1,
Email = 2,
Fax = 4
}
WPFの管理対象顧客ページのUIには、顧客の通信方法(印刷、電子メール、ファックス)の下に3つのチェックボックスがあります。私はその列挙型に各チェックボックスをバインドすることはできません、それは意味をなさない。また、ユーザーがその顧客をクリックして起きて昼食に行くと、コンテキストが悪い時間にそこに座ります。代わりに、これは私の思考プロセスです。
エンドユーザーがリストから顧客を選択します。コンテキストを新規作成し、その顧客を見つけてCustomerViewModelを返すと、コンテキストが閉じられます(ここでは簡単にリポジトリを残しています)。
using(MyContext ctx = new MyContext())
{
CurrentCustomerVM = new CustomerViewModel(ctx.Customers.Find(customerId));
}
今、ユーザーはそれらはまた、保存()メソッドを持っているCustomerViewModel、三のブール値のプロパティにバインドされているとして印刷、電子メール、ファックスボタンのチェックを外す/確認することができます。ここに行く。
public class CustomerViewModel : ViewModelBase
{
Customer _customer;
public CustomerViewModel(Customer customer)
{
_customer = customer;
}
public bool CommunicateViaEmail
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Email;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Email;
}
}
public bool CommunicateViaFax
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Fax;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Fax;
}
}
public bool CommunicateViaPrint
{
get { return _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print); }
set
{
if (value == _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print)) return;
if (value)
_customer.CommunicateViaPrint |= CommunicationMethod.Print;
else
_customer.CommunicateViaPrint &= ~CommunicationMethod.Print;
}
}
public void Save()
{
using (MyContext ctx = new MyContext())
{
var toUpdate = ctx.Customers.Find(_customer.Id);
toUpdate.CommunicateViaEmail = _customer.CommunicateViaEmail;
toUpdate.CommunicateViaFax = _customer.CommunicateViaFax;
toUpdate.CommunicateViaPrint = _customer.CommunicateViaPrint;
ctx.SaveChanges();
}
}
}
これは間違っていますか?
偉大な答え。あなたの返事をありがとう:EFチームメンバーの答えはここでは常に貴重です。 – JYL