0

私は次のものを持っています:

    if (chemexist == false) // conditionally creating WtrChem record
    {
      WtrChem wc = new WtrChem();
      wc.Contact = "John Smith";
      ..
      wc.Phone = ("800-888-9988");
      Db.WtrChem.Add(wc);
      Db.SaveChanges();
    }


    WtrChemDetail psw = new WtrChemDetail (); // creating details record for WtrChem
    psw.Comments = comment;
    ..
    .. 
    Db.WtrChemDetail.Add(psw);
    Db.SaveChanges();

コードは最初にマスターレコードを作成し、次に詳細レコードを作成します。私が持っているものは機能します。ベストプラクティスの観点から、上記のことを行うためのより効率的な方法があるかどうか疑問に思っています。

4

1 に答える 1

0

詳細がマスターのプロパティである場合は、これを少し異なる方法でモデル化することをお勧めします。

おそらくこのようなもの:

// Get the item. Include makes sure that you get the referenced detail as well.
WtrChem wc = Db.WtrChem.Include(x => x.Detail).SingleOrDefault();

if (wc == null) // creating WtrChem record
{
   // If it wasn't found, create and add
   wc = new WtrChem();
   Db.WtrChem.Add(wc);
}

wc.Contact = "John Smith";
..
wc.Phone = ("800-888-9988");

// Deal with the 
WtrChemDetail psw = new WtrChemDetail (); // creating details record for WtrChem
psw.Comments = comment;      
wc.Detail = psw;

Db.SaveChanges();

このアプローチを使用すると、マスターと詳細の間の参照が自動的にソートされます。

.Include(..)ラムダを機能させるには、usingステートメントを追加する必要があります。

using System.Data.Entity;
于 2012-09-26T21:44:44.480 に答える