NHibernate - 删除不在数据库中存在

时间:2010-08-27 10:59:20

标签: nhibernate fluent-nhibernate nhibernate-mapping

我正在尝试从一个到多个列表中删除一个项目并将其保留在数据库中。以下是我定义的实体:

public class SpecialOffer
{
    public virtual int SpecialOfferID { get; set; }
    public virtual string Title { get; set; }
    public virtual IList<SpecialOfferType> Types { get; private set; }

    public SpecialOffer()
    {
        Types = new List<SpecialOfferType>();
    }
}

public class SpecialOfferType
{
    public virtual SpecialOffer SpecialOffer { get; set; }
    public virtual Type Type { get; set; }
    public virtual int MinDaysRemaining { get; set; }

    #region composite id requirements
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is SpecialOfferType))
            return false;

        var t = (SpecialOfferType)obj;

        return SpecialOffer.SpecialOfferID == t.SpecialOffer.SpecialOfferID && Type.TypeID == t.Type.TypeID;
    }

    public override int GetHashCode()
    {
        return (SpecialOffer.SpecialOfferID + "|" + Type.TypeID).GetHashCode();
    }
    #endregion
}

public class Type
{
    public virtual int TypeID { get; set; }
    public virtual string Title { get; set; }
    public virtual decimal Price { get; set; }
}

使用以下流畅的映射:

public class SpecialOfferMap : ClassMap<SpecialOffer>
{
    public SpecialOfferMap()
    {
        Table("SpecialOffers");
        Id(x => x.SpecialOfferID);
        Map(x => x.Title);
        HasMany(x => x.Types)
            .KeyColumn("SpecialOfferID")
            .Inverse()
            .Cascade.All();
    }
}

public class SpecialOfferTypeMap : ClassMap<SpecialOfferType>
{
    public SpecialOfferTypeMap()
    {
        Table("SpecialOfferTypes");
        CompositeId()
            .KeyReference(x => x.SpecialOffer, "SpecialOfferID")
            .KeyReference(x => x.Type, "TypeID");
        Map(x => x.MinDaysRemaining);
    }
}

public class TypeMap : ClassMap<Type>
{
    public TypeMap()
    {
        Table("Types");
        Id(x => x.TypeID);
        Map(x => x.Title);
        Map(x => x.Price);
    }
}

我遇到的问题是,如果我从SpecialOffer.Types集合中删除一个项目,它会成功地从列表中删除它,但是当我尝试保存会话时,更改不会保留在数据库中。我假设这与连接表上的复合id有关,因为我过去能够成功地使用标准id。

如果有人能告诉我我做错了什么,我会很感激。感谢

1 个答案:

答案 0 :(得分:1)

我认为你必须1)当你从集合中删除时,将SpecialOffer.Types上的级联设置更改为Cascade.AllDeleteOrphan()和2)设置SpecialOfferType.SpecialOffer = null。由于集合是关系的反面,因此必须将SpecialOfferType上对SpecialOffer的多对一引用设置为null以使其成为孤儿,然后Cascade.AllDeleteOrphan将使其被删除。