2017-05-07 24 views
1

私は2つのテーブルを持っています。 AdsおよびUsers。 2つの間に関連テーブルがあります。私はこのEFが2つのテーブル間の関連テーブルに挿入されます

ListHell.ad na = new ListHell.ad(); 

string id = await context.Users 
    .Where(w => w.UserName == un) 
    .Select(w => w.Id) 
    .FirstOrDefaultAsync(); 
na.Users.Add(new User { Id = id }); 
lid = model.lid; 
na.catid = model.catid; 
na.title = model.title; 
na.description = model.description; 
na.phone = model.phone; 
na.address = model.address; 
na.amount = model.amount; 
na.datetime = DateTime.Now; 

context.ads.Add(na); 
context.SaveChanges(); 

しかし、その投げ例外がPRIMARY KEY制約 'PK_dbo.Users' の

違反を次のように新しい広告を挿入しています。オブジェクト 'dbo.Users'に 重複キーを挿入できません。重複キーの値は (6116bdbc-dbb7-4b13-be34-994cc4ad265c)です。ステートメントは 終了しました。

プロファイラでは、Usersテーブルに挿入されていることを示していますが、関連テーブルに挿入しています。

私はSOに多くの答えを見たが、すべてが

は私が何をしないのです、私を助けていないようですか?

答えて

1

既存のユーザー(あなたのデータベースから取得したIDを持つユーザーの新しいインスタンス)を再追加しているので、あなたはエラーを持っている:

string id = await context.Users 
    .Where(w => w.UserName == un) 
    .Select(w => w.Id) 
    .FirstOrDefaultAsync(); 
na.Users.Add(new User { Id = id }); // <- This is incorrect. 

あなたはこのようなものを2行をリファクタリングする必要があります。

var user = await context.Users 
    .Where(w => w.UserName == un) 
    .FirstOrDefaultAsync(); // <- We return a user instance from Database not the Id. 
na.Users.Add(user); // <- We add it to na Users collection 
関連する問題