user786
user786

Reputation: 4374

EF inserting into association table between two tables

I have two tables. Ads and Users. There is association table between the two. I am inserting new ad like this

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();

But its throwing exception following

Violation of PRIMARY KEY constraint 'PK_dbo.Users'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (6116bdbc-dbb7-4b13-be34-994cc4ad265c). The statement has been terminated.

In profiler it shows that it is inserting into the Users table but I am inserting in association table.

I have seen many answers on SO but seems all did not help me

what am I missing?

Upvotes: 1

Views: 35

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23240

You have the error because you're re-adding a existing User (a new instance of User with a Id retrieved from your Database) :

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.

You need to refactor those two lines like this:

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 

Upvotes: 1

Related Questions