2017-05-07 33 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 
相关问题