Servicestack OrmLite删除多对多

时间:2014-12-03 19:28:55

标签: servicestack ormlite-servicestack

我们说我有ListingEvent班和UserAccount班。

ListingEvent可以有多个UsersAttending,而UserAccount可以参加许多ListingEvents

这些课程如下:

public class UserAccount
{
    [AutoIncrement]
    [PrimaryKey]
    public int Id {
        get ;
        set;
    }

    public string Name {
        get ;
        set;
    }

    public UserAccount()
    {
        ListingEventsAttending = new List<UserAccountListingEvent> ();
    }

    [Reference]
    public List<UserAccountListingEvent> ListingEventsAttending {
        get;
        set;
    }
}

public class UserAccountListingEvent{
    [AutoIncrement]
    [PrimaryKey]
    public int Id {
        get;
        set;
    }

    public Model.AttendingStatus Status { get; set; }

    [References(typeof(UserAccount))]
    public int UserAccountId {
        get;
        set;
    }

    [References(typeof(ListingEvent))]
    public int ListingEventId {
        get;
        set;
    }
}

public class ListingEvent
{
    public ListingEvent()
    {
        UsersAttending = new List<UserAccountListingEvent>();
    }

    [AutoIncrement]
    [PrimaryKey]
    public int Id {
        get ;
        set;
    }

    public string Name { get; set; }

    [Reference]
    public List<UserAccountListingEvent> UsersAttending { get; set; }

    public void RemoveUserAttending(UserAccount user)
    {
        if (user == null)
        {
            return;
        }

        UsersAttending.RemoveAll(u => u.UserAccountId == user.Id);
    }
}

我得到一个具有UserAccount参与的ListEvent:

var listingEvent = db.LoadSingleById<Model.ListingEvent> (request.Id);

我可以看到具有正确ID的用户正在参加,因此请致电RemoveUserAttending以删除该用户。我现在可以看到用户没有参加,所以我打电话:

db.Save (listingEvent, references: true);

但是 - 现在当我再次获取ListingEvent时,用户又回来了。

所以我的问题是:

  1. 上述工作是否符合预期?
  2. 如果没有 - 我该怎么做?

1 个答案:

答案 0 :(得分:0)

db.Save()INSERTUPDATE个实体,即它们不DELETE

要删除,请检索要删除的实体或实体ID,并明确使用OrmLite的db.Delete* API,例如:类似的东西:

var removeUsersAttendingIds = listingEvent.UsersAttending
    .Where(u => u.UserAccountId == user.Id)
    .Select(u => u.Id);

db.DeleteByIds<UserAccountListingEvent>(removeUsersAttendingIds);