实体:
public class UserEntity {
// ...
public virtual Collection<UserEntity> Friends { get; set; }
}
流畅的API配置:
modelBuilder.Entity<UserEntity>()
.HasMany(u => u.Friends)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("FriendId");
m.ToTable("FriendshipRelation");
});
- Am I correct, that it is not possible to define the
Cascade Delete
in Fluent API? What is the best way to delete a
UserEntity
, for instanceFoo
?It looks for me now, I have to
Clear
theFoo
'sFriends
Collection, then I have to load all otherUserEntities
, which containFoo
inFriends
, and then removeFoo
from each list, before I removeFoo
fromUsers
. But it sounds too complicateda.Is it possible to access the relational table directly, so that I can remove entries like this
// Dummy code var query = dbCtx.Set("FriendshipRelation").Where(x => x.UserId == Foo.Id || x.FriendId == Foo.Id); dbCtx.Set("FriendshipRelation").RemoveRange(query);
My best solution for this problem for know is just to execute the raw sql statement before I call
SaveChanges
:dbCtx.Database.ExecuteSqlCommand( "delete from dbo.FriendshipRelation where UserId = @id or FriendId = @id", new SqlParameter("id", Foo.Id));
But the disadvantage of this, is that, if
SaveChanges
failes for some reason, theFriendshipRelation
are already removed and could not be rolled back. Or am I wrong?
57
的用户。这意味着我们必须在FriendshipRelation
中删除与此ID的所有关系。也就是说,我们删除所有与UserId = 57
的用户的好友,并删除所有其他用户与此用户的关系,其中FriendId = 57
。换句话说,我们删除了我所有的朋友,并删除了我作为朋友的所有关系。 - tenbits