Foreign key with EF 4 c#

I have a problem with foreign keys in EF 4.0.

I have a little game with a player. This Player can have some characters in the game.

So, when I want to add a character to database, I must set the foreign key "PlayerId".

This is my code, but kill when adding object in context model :

using (DatabaseModelContainer model = new DatabaseModelContainer())
    Character c = new Character();
    c.Player.Id = idPlayer;


Thank's for answers.


Strange things here

Character c = new Character();
c.Player.Id = idPlayer;//But instance c has no Player (well, I don't know the constructor of Character, but I may imagine there's no new Player() inside)

By the way, with the model you seem to have, you don't have to manage the FK as you do. You have to manage Reference (navigation) properties.

You can do it that way.

Character c = new Character{
   Player =  model.GetPlayerByid(idPlayer);//or something like that

Entity Framework have a method called Attach which may be what you are looking for. I think it can be used for updating foreign entities on an existing object.

MSDN: Attaching and Detaching Objects

Need Your Help

Draw 2 parallel lines

graphics drawing vector-graphics

How can I calculate the points to draw 2 parallel lines.

How can a path be stored in this kind of structure, and how to convert it to something else?

c++ c string winapi type-conversion

I'm having a look at the code of FastCopy. I want to add some option so that files are deleted to the recycle bin instead of permanently.