2017-05-07 36 views
1

我有兩個表。 AdsUsers。兩者之間有關聯表。我插入新的廣告這樣EF插入兩個表之間的關聯表

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表中,但是我正在插入關聯表中。

我曾見過這樣很多答案,但似乎都沒有幫我

我缺少什麼?

回答

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. 

您需要重構這兩條線是這樣的:

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 
相關問題