1

我建立一个应用程序周围的游戏旋转和我保持2种动作的名单在我的游戏对象:MVC modelbuilding:在表的多个外键,代码首先EF

public class Game 
{ 
    public int Id {get;set;} 

    List<Action> ActiveActionList {get;set} 
    List<Action> PassiveActionList {get;set;} 
    ... (several other variables) 
} 

public class Action 
{ 
    public int Id {get;set;} 
    Game Game {get;set;} 
    ...(several other variables) 
} 

的这里的想法是,一个动作或者是在被动或主动的ActionList(从来没有在两者),我把在行动上的一侧为基准为好,使之与行动的工作时,我可以这样说:

if (currentAction.Game.Id == someVariable) 
... 

我遇到的问题是,当我看向所创建的数据库。 “操作”表中有所有正常的变量我的预期,但对于游戏对象引用它显示下列:

  • Game_Id
  • Game_Id1
  • Game_Id2

我猜测我应该在DbContext中的模型构建器重写中做一些事情,以确保只有1列引用Game_Id。

我试着使用:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Actie>().HasRequired<Spel>(s => s.Spel).WithMany(a => a.Actielijst).HasForeignKey(a => a.Spel).WillCascadeOnDelete(false); 
     base.OnModelCreating(modelBuilder); 
    } 

基于此岗位(Entity Framework 4.1 InverseProperty Attribute and ForeignKey),但现在我得到另一个错误:

国外关键部件“游戏”是不是一个声明的属性在类型'行动'上。验证它没有被明确地从模型中排除,并且它是一个有效的基本属性。

我不知道如何,因为我希望我只是用在上面的模型构建器错误的配置解决这个问题,所以我希望这里有人能指出我吧:)

回答

1

一些更多的研究,我发现后这是根本不可能有多个列表中的一个对象是指在填充列表中的objectype一个键。处理这个问题的方法是使用如下所示的DataAnnotation'InverseProperty':https://stackoverflow.com/a/25366822/3191144

这意味着需要为每个要保留的列表拥有一个引用对象。对于我来说,我必须做到以下几点:

public class Game 
{ 
    public int Id {get;set;} 

    [InverseProperty("Game")] 
    List<Action> ActiveActionList {get;set;} 
    [InverseProperty("PassiveGame")] 
    List<Action> PassiveActionList {get;set;} 
    ... (several other variables) 
} 

public class Action 
{ 
    public int Id {get;set;} 
    Game Game {get;set;} 
    Game PassiveGame {get;set;} 
    ...(several other variables) 
} 

不幸的是,这也意味着我将有一个列,它是几乎总是空(PassiveActions是罕见的比ActiveActions),但我想这是它的工作方式。对于两个以上的列表,我认为最好是更改体系结构或使用子类来避免加载列,以便简单地跟踪项目所在的列表。

如果有人找到一种方法来获得1列在动作表为纽带,以游戏和其它方法来跟踪这两个列表中,请不要回复:)