Amr Elgarhy
Amr Elgarhy

Reputation: 68912

Insert a new record in one to one relational tables

I have 2 tables for Users, one to hold User common info and one for extra info, they have one to one relation with UserId field.

Users:

UserId >> Primarykey auto increment  
UserName  
Password

UsersInfo:

UserId >> Primarykey  
MoreInfo

in my application , when the user register a new account we insert a row in Users table, and later if he wanted to change some info, we need to add to UsersInfo table.

The problem I am facing is that when I try to insert in the UsersInfo table it always tell me that UserId can't be null. while I have this userId set before i call saveChanges.

var info = new UserInfo { UserId = userId, MoreInfo = text };
context.UserInfo.Add(info);

I don't know if the problem in EF or in db, so any info or something to check will help.

Upvotes: 0

Views: 238

Answers (2)

VMykyt
VMykyt

Reputation: 1629

This is not a solution but workaround. It probably will work:

Users:
----
UserId >> Primary key & Auto increment
UserName
Password

UsersInfo:
----
UsersInfoId >> Primary key auto increment
UserId >> Foreign key & Unique constraint (for one-to-one relation)
MoreInfo

Upvotes: 2

Kumar Kush
Kumar Kush

Reputation: 2586

First thing, you need not use two separate tables, except when u have multiple sets of extra info per user. If you use single table, then a simple UPDATE query will ease the things.

If you want to go your way, first test whether userId is null or having some value. If it is null or empty, you are bound to get the error you mentioned.

See if it helps.

Upvotes: 1

Related Questions