10

私は3つのテーブルを持っています、

1)顧客(Id、Name、bla bla)

2)CustomerGroups(GroupId、GroupName)

3)CustomerInGroups(CustomerId、GroupId)

using (var context = DataObjectFactory.CreateContext())
{                
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}

CustomerInGroupsにレコードを追加するにはどうすればよいですか?EntityFrameworkは、このような多対多のマッピングテーブルのエンティティを生成しません

編集:

CustomerとCustomerGroupsの両方のId列が自動インクリメントに設定されています。

つまり、CustomersGroupテーブルには、

Id          Name
----------------------------
1           Normal
2           VIP

ポスターの1つが示唆したように、私はこれをやってみました:

entity.CustomerGroups = new List<CustomerGroup>
{
    new CustomerGroup {Id = 2 }
};
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;

ただし、これを行ったとき、次のようにマッピングテーブルにレコードを作成する代わりに、次のようにします。

CustomerId          GroupId
----------------------------
1                   2

私が得たのは

CustomerInGroups
    CustomerId          GroupId
    ----------------------------
    1                   3

CustomerGroups
    Id          Name
    ----------------------------
    1           Normal
    2           VIP
    3           NULL

それは実際に私のCustomerGroupsテーブルに別のエントリを作成しましたが、それは私が望むものではありません

4

3 に答える 3

8

プロパティに含まれるものを含めなかったので、少し盲目的に飛んでいますentity。ただし、 との関係のプロパティが必要ですCustomerGroups。関連付けたいグループでそのプロパティを設定するだけです。たとえば、これは新しいグループ名「foo bar」を作成し、エンティティをそのグループに関連付けます。

using (var context = DataObjectFactory.CreateContext())
{
    entity.CustomerGroups = new List<CustomerGroup> { GroupName = "Foo bar" };
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}

リレーションシップが正しく設定されている場合、EF は自動的にテーブルにレコードをCustomerGroups挿入し、テーブルにリレーションシップを挿入しCustomerInGroupsます。

編集:

CustomerGroup既存の顧客を新しい顧客に追加しようとしている場合。最初にデータベースからを取得してCustomerGroupから、挿入する Customer エンティティに追加します。

using (var context = DataObjectFactory.CreateContext())
{
    var customerGroups = context.CustomerGroups.Where(...).ToList(); // get your CustomerGroup object(s) here, and ensure it's enumerated with ToList()
    entity.CustomerGroups = customerGroups;
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}
于 2013-03-07T04:22:36.713 に答える
2

既存の顧客を _existing グループに割り当てようとしていて、CustomerGroup オブジェクトが ICollection を公開すると想定している場合は、次の手順を実行します。

(var context = DataObjectFactory.CreateContext())
{
    context.Customers.Add(entity);
    var group = context.CustomerGroups.Find(2); // or however you retrieve the existing group
    group.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id
}

Find() メソッドは、Id で検索する Entity Framework Code First (DbContext) の方法です。「適切な」 ObjectContext の方法を頭のてっぺんに思い出すことはできませんが、 .Single(g => g.Id == 2) も機能します。

理想的には、エンティティがどのようにマッピングされているかについてより良いアイデアを提供して、エンティティをどのように関連付けているかを把握できるようにしてください。

于 2013-03-07T10:16:28.263 に答える