2

たとえば、カードをセットに関連付ける場合、次のようになります。

public class Card
{

    public virtual int CardId { get; set; }

    // belongs to a Set
    public virtual int SetId { get; set; }
    public virtual Set Set { get; set; }
 }

Set と SetId の両方が必要なのはなぜですか?

4

1 に答える 1

5

設定する必要はありません。「Set」を仮想オブジェクトとして指定するだけで、実行時にナビゲーション プロパティで上書きできます。Entity Framework は、オブジェクト ドメイン モデルからアクセスできない場合でも、テーブルに外部キー "SetId" を自動的に作成します。

設定する必要はありませんが、個人的には、関連するオブジェクトをインスタンス化する代わりに int との関係を指定できるため、オブジェクトの基礎となる外部キー ID にアクセスできるのが好きです。

編集:サンプルコードの追加

次のクラスがあります。

public class Card
    {
        public virtual int CardId { get; set; }

        // belongs to a Set
        public virtual int SetId { get; set; }
        public virtual Set Set { get; set; }
    }

    public class Set
    {
        public int SetId { get; set; }
        public string SetName { get; set; }
    }

私は次のようなことをすることができます:

    var context = new Context(); //Db Code-First Context

    var set = context.Sets.First(s => s.SetName == "Clubs"); //Get the "Clubs" set object

    //Assign the set to the card
    var newCard = new Card();
    newCard.Set = set; 

    //Save the object to the databae
    context.Cards.Add(newCard);
    context.SaveChanges();

または、次のようにします。

//Assign the set ID to the card
var newCard = new Card();
newCard.SetId = 4; 

//Save the object to the databae
context.Cards.Add(newCard);
context.SaveChanges();

そして、オブジェクトは同じ方法で保存されます。

ViewModel をコントローラーに投稿しているとします。オブジェクト全体ではなく、ビューのドロップダウン リストから選択した ID を渡す方が簡単です。

于 2013-02-11T17:42:11.773 に答える