我在代码优先使用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为我创建了db表,只有ClassA表。我没有可以存储团队和级别数据的表格。当我运行Add-Migration命令时,创建的迁移文件为空,EF认为没有挂起的更改。此外,当我运行Update-Database命令时,EF表示没有挂起的更改。
我在这里缺少什么?
答案 0 :(得分: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,"}
现在,您可以通过
获得团队2中的两个var players = context.Players.Where(p=>p.Teams.Contains(",2,"));