私はEntityFramework4.0を試していますが、これがケースの最も単純化されたバージョンです-
私は次の2つの関連するテーブルを持っています-
住所
ID
市
クライアント
ID
アドレスID
名
ComboBoxにアドレスをロードしました。テキストボックスにクライアント名を入力し、コンボボックスからクライアントのアドレスとしてアドレスを選択して、[保存]ボタンをクリックするだけです。クライアントをクライアントテーブルに保存したい。これが私が試したことです-
/*loads Addresses to the ComboBox*/
private void LoadData()
{
using (CAEntities ctx = ModelAccess.GetContext())
this.AddressList = ctx.Addresses.ToList();
}
/*(tries) to insert the Client to the database*/
private void Save()
{
/*here this.Client is the Client object that is instantiated & initialized
by previous code and this.Address is the SelectedItem of the ComboBox*/
this.Client.Address = this.Address;
using (CAEntities ctx = ModelAccess.GetContext())
{
ctx.Clients.AddObject(this.Client);
ctx.SaveChanges();
}
}
Programming EntityFrameworkのJulieLermanは、次のように述べています。...Because the
entities are joined, you can add either entity, and it will bring along the rest of the graph...
しかし、私が持っているのは、「EntityKeyプロパティは、プロパティの現在の値がnullの場合にのみ設定できる」というInvalidOperationExceptionです。
使用する場合-
this.Client.AddressId = this.Address.Id;
それ以外の -
this.Client.Address = this.Address;
クライアントはデータベースに完全に挿入されます。しかし、私もエンティティを直接相互に関連付けることができるはずだと思いますよね?
問題は、作成している別のコンテキストに関連していると思いました。だから私はこれを試しました-
private void Save()
{
this.Client.Address = this.Address;
using (CAEntities ctx = ModelAccess.GetContext())
{
ctx.Addresses.Attach(this.Address);
ctx.SaveChanges();
}
}
しかし今回は、「一時的なEntityKey値を持つオブジェクトをオブジェクトコンテキストにアタッチできません」というInvalidOperationExceptionが発生します。それで、私がここで間違っているのは何ですか?前もって感謝します。