我使用 Entity Framework Code First 和最新的 Entity Framework 版本创建了自己的数据库模型。
我有这堂课:
[DataContract]
public class User
{
[DataMember]
public int UserId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string InterestIn { get; set; }
[DataMember]
public virtual ICollection<User> Friends { get; set; }
[DataMember]
public virtual ICollection<User> FromWhomIsFriend { get; set; }
[DataMember]
public virtual ICollection<Activity> WantsToDo { get; set; }
[DataMember]
public virtual ICollection<Message> MessagesSent { get; set; }
[DataMember]
public virtual ICollection<Message> MessagesReceived { get; set; }
public override string ToString()
{
string output = string.Empty;
output = String.Format("UserId: {0}, Name: {1}, Age: {2}, City: {3}, " +
"Country: {4}, Email: {5}, InterestIn: {6}",
UserId, Name, Age, City, Country, Email, InterestIn);
return output;
}
}
及其配置类:
class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
Property(d => d.Name).IsRequired();
Property(d => d.Age).IsRequired();
Property(d => d.City).IsRequired();
Property(d => d.Country).IsRequired();
Property(d => d.Email).IsRequired();
Property(d => d.InterestIn).IsRequired();
HasMany(d => d.MessagesSent).WithRequired(l => l.SentByUser).WillCascadeOnDelete(false);
HasMany(d => d.MessagesReceived).WithRequired(l => l.SentToUser).WillCascadeOnDelete(false);
HasMany(d => d.Friends).
WithMany(d => d.FromWhomIsFriend).
Map(c =>
{
c.ToTable("UserFriends");
c.MapLeftKey("UserId");
c.MapRightKey("FriendId");
});
HasMany(d => d.WantsToDo).
WithMany(a => a.Users).
Map(t =>
{
t.ToTable("UserActivities");
t.MapLeftKey("UserId");
t.MapRightKey("ActivityId");
});
}
}
表示这种多对多自我关系:
现在我有一个问题:我不知道如何删除朋友关系。使用 SQL,我将执行以下操作:
DELETE FROM UserFriend
WHERE (userId = user1_id AND friendId = friend1_id) OR
(userId = friend1_id AND friendId = user1_id)
user1_id
:是要删除好友关系的用户。
friend1_id
: 是 user1 想要删除为好友的好友。
我该怎么做?