【发布时间】:2018-08-29 00:29:47
【问题描述】:
我首先是 EntityFramework 代码的新手。所以我正在运行一些简单的测试来学习。我创建了两个类:Team 和 Player,假设它们具有多对多关系。我还启用了迁移并添加了一些种子数据。当我运行 update-database 时,我看到种子数据填充了 Teams 和 Players 表,但 TeamPlayers 表为空。有什么线索可以说明代码中有什么问题吗? (为简单起见,我已在此处删除了包装内含物)
namespace CodeFirst_onetomany.Models
{
public class Team
{
public Team()
{
this.Players = new HashSet<Player>();
}
public int Id { get; set; }
public string TeamName { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
}
namespace CodeFirst_onetomany.Models
{
public class Player
{
public Player()
{
this.Teams = new HashSet<Team>();
}
public int Id { get; set; }
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
}
namespace CodeFirst_onetomany.Models
{
public class MyContext : DbContext
{
public MyContext() : base("MyDbOneToMany")
{
}
public DbSet<Team> Teams { get; set; }
public DbSet<Player> Players { get; set; }
}
}
namespace CodeFirst_onetomany.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<CodeFirst_onetomany.Models.MyContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CodeFirst_onetomany.Models.MyContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
context.Teams.AddOrUpdate(t => t.TeamName, new Team() { TeamName = "AC Milan" });
context.Teams.AddOrUpdate(t => t.TeamName, new Team() { TeamName = "Barcelona" });
context.SaveChanges();
context.Players.AddOrUpdate(p => new { p.FirstName, p.LastName },
new Player()
{
FirstName = "Paolo",
LastName = "Maldini",
Teams = new List<Team>() { context.Teams.FirstOrDefault(t => t.TeamName == "AC Milan") }
});
context.Players.AddOrUpdate(p => new { p.FirstName, p.LastName },
new Player()
{
FirstName = "Leo",
LastName = "Messi",
Teams = context.Teams.ToList()
});
context.SaveChanges();
}
}
}
编辑:所以我删除了 HashSets(感谢 @Harald Coppoolse 提供的信息)并开始将信息存储在变量中以便我可以调试它......我还在最后添加了两行将团队添加到玩家。所以我部分有:
context.Players.AddOrUpdate(p => new { p.FirstName, p.LastName }, maldini);
context.Players.AddOrUpdate(p => new { p.FirstName, p.LastName }, messi);
context.Players.FirstOrDefault(p => p.FirstName == "Paolo").Teams = shouldBeMilan;
context.Players.FirstOrDefault(p => p.FirstName == "Leo").Teams = shouldBeBarcaMilan;
context.SaveChanges();
它现在可以工作了。所以我想必须在 EF 中手动添加球员和球队之间的关系,我们不能依赖对象创建(即使用 new)。我不知道为什么!
【问题讨论】:
-
我认为您必须手动添加到映射表,就像您为 Team 和 Player 类所做的那样。
标签: asp.net-mvc entity-framework model-view-controller ef-code-first