简体   繁体   中英

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;

    model.CharacterJeu.AddObject(c);
    model.SaveChanges();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM