【问题标题】:Servicestack OrmLite deleting many to manyServicestack OrmLite 删除多对多
【发布时间】:2014-12-04 04:31:17
【问题描述】:

假设我有一个ListingEvent 类和一个UserAccount 类。

ListingEvent 可以有多个UsersAttendingUserAccount 可以参加多个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);
    }
}

我得到一个 ListEvent,我的 UserAccount 参加了:

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

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

db.Save (listingEvent, references: true);

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

所以我的问题是:

  1. 以上是否应该按预期工作?
  2. 如果没有,我应该怎么做?

【问题讨论】:

    标签: servicestack ormlite-servicestack


    【解决方案1】:

    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);
    

    【讨论】:

    • 这有点问题,因为现在我必须从我的域中删除该逻辑,这将使它有点乏力 - 人们如何处理这个问题?我应该考虑使用更改跟踪的 orM 吗? ://
    • OrmLite 一直是一个毫不奇怪的 ORM,它与 SQL 保持着高度的相似性,也就是说,您需要对 SQL 或任何 Micro ORM 采取非常相似的方法。如果您改为使用 blobbed(即不使其成为 [Reference] 类型),那么您的方法将起作用。否则,如果您愿意,请确保您可以使用更重的 ORM 和更改跟踪。
    • 干杯 - 会增加一些代码 - 很长时间没有使用 NHibernate :p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多