简体   繁体   中英

EF not creating table for virtual properties

I'm using EF with code-first. My model contains two virtual properties like:

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 has created db tables for me there is only ClassA table. There is no table I can store Teams and Levels data. When I run Add-Migration command, created migration file is empty is EF thinks there is no pending changes. Also when I run Update-Database command EF says there is no pending changes.

What am I missing here?

Why not do:

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; }
}

In case you really want 'light weight' (please don't) you could do:

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; }
}

Say you have these in your context

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

Now, you could get both in team 2 by

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

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