简体   繁体   English

带有EF 4 c#的外键

[英]Foreign key with EF 4 c#

I have a problem with foreign keys in EF 4.0. 我在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". 因此,当我想向数据库添加字符时,必须设置外键“ 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. 顺便说一下,有了您似乎拥有的模型,您就不必像以前那样管理FK。 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. 实体框架有一个称为Attach的方法,这可能是您要寻找的。 I think it can be used for updating foreign entities on an existing object. 我认为它可以用于更新现有对象上的外国实体。

MSDN: Attaching and Detaching Objects MSDN: 附加和分离对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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