实体框架6代码优先关系/表创建问题 [英] Entity Framework 6 Code First Relationship/table creation issues

查看:73
本文介绍了实体框架6代码优先关系/表创建问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行Code First迁移,但是其中的一个模型/表在迁移时表现得很奇怪。

I'm trying to do a Code First migration, but one of the models/tables behave pretty weird when I migrate.

Team and Tournament制作了一个新表,以引用什么团队属于哪个锦标赛以及相反的方式-这就是我想要的。

Team and Tournament makes a new Table to reference what team belongs to what tournament and the other way around - That's totally what I want.

我正在尝试对Matchup和Team进行相同的操作,为二者都定义了集合,但由于某种原因,它在Matchup中创建了单个属性TeamId,这是一个问题,因为对决应该能够存储多个团队。

I'm trying to do the same with Matchup and Team, defining collections for both, but for some reason it makes a single property, TeamId, in Matchup which is a problem since a Matchup should be able to store more than one Team.

清晰的屏幕截图

预先感谢。

推荐答案

当同一文件中有多个引用时,您需要告诉EF如何建立关系。我更喜欢流利的代码:

You need to tell EF how to do the relationships when you have multiple references in the same file. I prefer fluent code for this:

修复模型:

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

    public int WinnerId { get; set; }  // FK by convention
    public Team Winner { get; set; }
    public Tournament Tournament { get; set; }
    public ICollection<Team> Teams { get; set; }
}

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

    public ICollection<Player> Players{ get; set; }
    public ICollection<Matchup> Matchups{ get; set; }
    public ICollection<Matchup> MatchupWinners{ get; set; }
    public ICollection<Tournament> Tournaments{ get; set; }
}


// Configure 1 to many
modelBuilder.Entity<Matchup>()
    .HasOptional(m => m.Winner)
    .WithMany(p => p.MatchupWinners)
    .HasForeignKey(p => p.WinnerId);

// Configure many to many
modelBuilder.Entity<Matchup>()
        .HasMany(s => s.Teams)
        .WithMany(c => c.Matchups)
        .Map(t =>
                {
                    t.MapLeftKey("MatchupId");
                    t.MapRightKey("TeamId");
                    t.ToTable("MatchupTeam");
                });

但是您也可以使用注释:

But you can also do it with annotations:

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

    public ICollection<Player> Players{ get; set; }

    [InverseProperty("Teams")]
    public ICollection<Matchup> Matchups{ get; set; }

    [InverseProperty("Winner")]
    public ICollection<Matchup> MatchupWinners{ get; set; }

    public ICollection<Tournament> Tournaments{ get; set; }
}

这篇关于实体框架6代码优先关系/表创建问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆