views:

19

answers:

1

Hi, i'm trying to remove an item from a one to many list and have it persist in the database. Here are the entities i have defined:

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

With the following fluent mappings:

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

The problem i have is that if i remove an item from the SpecialOffer.Types collection it successfully removes it from the list but when i try to save the session the change is not persisted in the database. I'm assuming this is something to do with the composite id on the join table since i have been able to do this successfully in the past with a standard id.

I'd appreciate it if someone could show me what i'm doing wrong. Thanks

+1  A: 

I think you have to 1) Change the cascade setting on SpecialOffer.Types to Cascade.AllDeleteOrphan() and 2) set SpecialOfferType.SpecialOffer = null when you remove it from the collection. Since the collection is the inverse side of the relationship, the many-to-one reference to SpecialOffer on SpecialOfferType has to be set to null to make it an orphan, then Cascade.AllDeleteOrphan will cause it to be deleted.

Jamie Ide