0

I create 2 table in sql server 2008

table 1 : User( UserID,Name, FirstName,Login, Password...) , PK : UserID
table 2 : SessionUser(UserID, Date, Adress) , PK : UserID

The relationship between the two tables is set in sql server 2008, with 1 to 1 relationship and the foreign key is in the table SessionUser (FK: userID)
There are users in the User table (full lines)
when I tried to add a session in the session table it shows me this error:

Entities in 'DistributionSSEntities.SessionUser ' participate in the 'FK_SessionUser_User ' relationship. 0 related 'User ' were found. 1 'User ' is expected.

code:

DistributionSSEntities db = new DistributionSSEntities();
SessionUser sessionUser = new SessionUser();

            sessionUser.UserID = 12; // this ID existe in User table
            sessionUser.Date = "12-12-2012";
            sessionUser.AdressIP = "192.168.1.1";


            db.AddToSessionUser(sessionUser);
            db.SaveChanges();

how to resolve this problem Thanx.

Ankur
  • 5,086
  • 19
  • 37
  • 62
Ibra
  • 31
  • 3
  • possible duplicate of [Entity Framework EntityKey / Foreign Key problem](http://stackoverflow.com/questions/1011519/entity-framework-entitykey-foreign-key-problem) – CodeCaster May 02 '13 at 11:21

1 Answers1

0

Just setting the UserID won't do the trick.

You can either:
- select the user from the database and then set the User property
- create a new User with the desired ID and attach it to the context
- or, set the foreign key reference directly:

sessionUser.UserReference.EntityKey = new System.Data.EntityKey(sessionUser.UserReference.RelationshipSet.EntityContainer.Name + "." + sessionUser.UserReference.TargetRoleName, "ID", id);

It's a bit long, but you can make it into an extension method as it comes in handy.

Darko Kenda
  • 4,781
  • 1
  • 28
  • 31