我有一个带有实体框架6的Web API应用程序。 我有2个实体 - 玩家和匹配他们之间的多对多关系:
public class Player {
public string PlayerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Match> Matches { get; set; }
}
public class Match {
public string MatchId { get; set; }
public DateTime DateTime { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
这就是我的DBContext的样子:
public class FIFA15RankingContext : DbContext {
public DbSet<Player> Players { get; set; }
public DbSet<Match> Matches { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Player>()
.HasMany(t => t.Matches)
.WithMany(t => t.Players)
.Map(m => {
m.ToTable("PlayerMatches");
m.MapLeftKey("PlayerId");
m.MapRightKey("MatchId");
}
);
base.OnModelCreating(modelBuilder);
}
}
EF为幕后创建了PlayerMatches(PlayerId,MatchId)。
这是我的MatchesController(由VS 2013搭建):
// POST: api/Matches
[ResponseType(typeof(Match))]
public async Task<IHttpActionResult> PostMatch(Match match)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
db.Matches.Add(match);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (MatchExists(match.MatchId))
return Conflict();
else
throw;
}
return CreatedAtRoute("DefaultApi", new { id = match.MatchId }, match);
}
我希望能够创建新匹配并与现有用户关联。 我无法以任何其他方式使其工作,但在db.Matches.Add(匹配)之前添加此代码(闻起来很糟糕):
var playersFromDB = new List<Player>();
if (match.Players != null) {
foreach (var p in match.Players) {
playersFromDB.Add(db.Players.Find(p.PlayerId));
}
}
match.Players = playersFromDB;
我做错了什么?
答案 0 :(得分:0)
如果数据库中已存在所有播放器,则可以将它们附加到dbcontext,而不是从db。
加载 if (match.Players != null) {
foreach (var player in match.Players) {
db.Players.Attach(player);
}
}
答案 1 :(得分:0)
手动附加User
个实体并将其状态设置为Unchanged
foreach( var p in match.Players )
{
db.Entry( p ).State = EntityState.Unchanged;
}