I have three models, User, Room, and PlayerRoom defined as such:
public class User
{
public int id { get; set; }
public string UserName { get; set; }
//flags user to be deleted when room is no longer available
public bool temporaryUser { get; set; }
[JsonIgnore]
public bool permanent { get; set; }
}
public class Room
{
public int id { get; set; }
public string RoomName { get; set; }
[JsonIgnore]
public int CreatedById { get; set; }
public virtual User CreatedBy { get; set; }
}
public class PlayerRoom
{
public int id { get; set; }
[JsonIgnore]
public int RoomId { get; set; }
public virtual Room Room { get; set; }
[JsonIgnore]
public int UserId { get; set; }
public virtual User User { get; set; }
}
What i'm trying to accomplish is setting up the models so that when a User
is deleted or when a Room
is deleted, all associated PlayerRoom
get deleted.
Currently when I generate the migration and run update-database
I get the error:
Introducing FOREIGN KEY constraint 'FK_dbo.Rooms_dbo.Users_CreatedById' on table 'Rooms' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
From what research I've done it is because PlayerRoom
can be deleted in multiple ways from a cascade however, this is the intended behavior.
How can I get the migration tool to generate a migration that will not throw this error?
Thanks!
I ended up altering my classes to make them a bit more restrictive, which in this case actually works out better. I removed the PlayerRoom
object and moved the Room
reference onto the user object.
public class User
{
public int id { get; set; }
public string UserName { get; set; }
//flags user to be deleted when room is no longer available
public bool temporaryUser { get; set; }
public bool? isHost { get; set; }
[JsonIgnore]
public int? RoomId { get; set; }
public virtual Room Room { get; set; }
[JsonIgnore]
public bool permanent { get; set; }
}
public class Room
{
public int id { get; set; }
public string RoomName { get; set; }
}
By moving Room
to the User instead of on a separate object it restricts users to only be in one Room
and gets rid of my cascading delete issue
gets rid of my cascading delete issue
EF using Code First sets up cascading by default to be on. To turn it off from the model one can either strategically place 'WillCascadeOnDelete` off the entity in question:
.WillCascadeOnDelete(false);
or globally
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.