2014-10-16 85 views
0

我以代码优先使用EF。我的模型包含两个虚拟属性,如:EF不为虚拟属性创建表

ClassA 

public int Id { get; set; } 
public string Name { get; set; } 
public virtual List<int> Teams { get; set; } 
public virtual List<int> Levels { get; set; } 

EF已为我创建数据库表只有ClassA表。没有我可以存储球队和关卡数据的表格。当我运行Add-Migration命令时,创建的迁移文件为空,EF认为没有挂起的更改。另外,当我运行更新数据库命令EF说没有挂起的更改。

我在这里错过了什么?

+0

您不能将int作为映射到表的实体。 – 2014-10-16 11:34:37

+0

为什么会有额外的表格?你没有定义它们,或者至少没有在你的代码中显示它们。 – Maarten 2014-10-16 11:34:48

回答

2

为什么不这样做:

public class Team { 
    public int Id { get; set; } 
    public virtual ICollection<Player> Players { get; set; } 
} 
public class Level { 
    public int Id { get; set; } 
    public virtual ICollection<Player> Players { get; set; } 
} 
public class Player { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Team> Teams { get; set; } 
    public virtual ICollection<Level> Levels { get; set; } 
} 

如果你真的想 '重量轻'(请不要),你可以这样做:

public class Player { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    //use comma separated values (starting and ending with ,) 
    public string Teams { get; set; } 
    public string Levels { get; set; } 
} 

说你有这些你背景

var player1 = new Player(){Teams = ",1,2,"} 
var player2 = new Player(){Teams = ",3,2,"} 

现在,你可以同时得到t eam 2 by

var players = context.Players.Where(p=>p.Teams.Contains(",2,"));