So, in my model, I have the Player class and the Game class, Game has 2 required players, for example: (along with some other fields that I have not included here)
public class Game
{
public Player Player1 { get; set; }
[Required]
public int Player1Id { get; set; }
public Player Player2 { get; set; }
[Required]
public int Player2Id { get; set; }
}
When I try to transfer this model to the database, I get the following error:
Representation of the FOREIGN KEY constraint "FK_dbo.Games_dbo.Players_Player2Id" in the "Games" table may cause loops or several cascading paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION or change other FOREIGN KEY constraints.
(The answer to https://stackoverflow.com/a/16710/ ... gives a good explanation of why I am getting this error.)
To avoid this error, I added the following free API code:
modelBuilder.Entity<Game>()
.HasRequired(c => c.Player1)
.WithMany()
.HasForeignKey(c => c.Player1Id)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Game>()
.HasRequired(c => c.Player2)
.WithMany()
.HasForeignKey(c => c.Player2Id)
.WillCascadeOnDelete(false);
, Player, .
: , NULL. , . , , , .
, - . ( , . Player1Id ( Player2Id) null, , )
, SO Seed().
context.Database.ExecuteSqlCommand("CREATE TRIGGER Game_Player_Del on dbo.Players instead of delete as " +
"set nocount on " +
"delete from dbo.Games where Player1Id in (select Id from deleted) or " +
"Player2Id in (Select Id from deleted) " +
"delete from dbo.Players where Id in (select Id from deleted)");
, , , , .
, , -? ( , )
Edit: , , - , , Player1Id Player2Id Player.Id, , , ( ) , , framework .
2: ( usr) :
:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
repo.deletePlayer(id);
return RedirectToAction("Index");
}
Repo:
public void deletePlayer(int id)
{
using (var context = new TennisContext())
{
player = context.Players.Find(id);
context.Entry(player).State = EntityState.Deleted;
context.SaveChanges();
}
}
3: , .
:
public void deletePlayer(int id)
{
using (var context = new TennisContext())
{
player = context.Players.Find(id);
List<Game> playerGames = context.Games.Where(g => g.Player1Id == id || g.Player2Id == id).ToList();
foreach (Game g in playerGames)
{
context.Entry(g).State = EntityState.Deleted;
}
context.Entry(player).State = EntityState.Deleted;
context.SaveChanges();
}
}