DbContext返回一些空字段

时间:2017-02-03 14:23:49

标签: c# database entity-framework

问:当我尝试从_Db返回数据时,我在List属性中获取了null对象,我想知道为什么其他属性被正确返回,而{{1不是吗?

问题说明:我有List班级 ApplicationDbContext财产。使用以下public IDbSet<Player> Players { get; set; }类:

ApplicationDbInitializer

我的public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { context.Players.Add(new Player { PlayerName = "john", PlayerSkills = new List<string> { "a", "b" } }); context.Players.Add(new Player { PlayerName = "Wuli", PlayerSkills = new List<string> { "c", "d" } }); base.Seed(context); } } 课程如下:

Player

我对数据的请求如下:

public class Player
{
    [Key]
    public int Id { get; set; }
    public string PlayerName { get; set; }
    public List<string> PlayerSkills { get; set; }
 }

它绝对正确地返回public IEnumerable<Player> Get() { return _Db.Players; } Id,但PlayerName列表会null

PlayerSkills通过以下方式在与_Db相同的Controller类中进行初始化:

Get()

1 个答案:

答案 0 :(得分:3)

SQL中存在可以存储值集合的字段类型。如果您要查看由EF生成的表格,您将看不到PlayerSkills。创建脚本看起来像

CREATE TABLE [dbo].[Players] (
    [Id] [int] NOT NULL IDENTITY,
    [PlayerName] [nvarchar](max),
    CONSTRAINT [PK_dbo.Players] PRIMARY KEY ([Id])
)

这就是为什么你不能在PlayerSkills字段中获取任何数据的原因。如果要在SQL数据库中存储一对多关系,则需要第二个表来存储玩家技能和与这些技能相关的玩家ID。如果你想避免技能重复,甚至两个表 - 一个用于技能,一个用于将玩家映射到技能的联结表。

没有联结表(如果你不想要外键的显式属性,那么你的选项是流畅的映射而不是属性映射):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Player>()
        .HasMany(p => p.PlayerSkills).WithRequired();

    base.OnModelCreating(modelBuilder);
}

PlayerSkills

public class PlayerSkill
{
    public int Id { get; set; }
    public string Name { get; set; }
}

播放器

public class Player
{
    public int Id { get; set; }
    public string PlayerName { get; set; }
    public virtual List<PlayerSkill> PlayerSkills { get; set; }
}

使用联结表

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Player>()
        .HasMany(p => p.PlayerSkills)
        .WithMany()
        .Map(j => j.MapLeftKey("PlayerId")
                   .MapRightKey("PlayerSkillId")
                   .ToTable("PlayerToSkill"));

    base.OnModelCreating(modelBuilder);
}