Sasha
Sasha

Reputation: 20824

NHibernate and HasMany mapping

i have trivial mapping for two entities: poll and polloption

Poll:

public class PollMap : ClassMap<Poll>
{
    public PollMap() {
        Id(x => x.Id);

        Map(x => x.Content);

        HasMany(x => x.PollOptions).Cascade.All();
    }
}

PollOption:

public class PollOptionMap : ClassMap<PollOption>
{
    public PollOptionMap() {
        Id(x => x.Id);

        Map(x => x.Content);

        References(x => x.Poll);
    }
}

in test code im trying to remove the first polloption of poll entity

Test code:

    [Transaction]
    public ActionResult Add() {

        var poll = new Poll() {
            Content = "poll",
            PollOptions = new List<PollOption>() {
                new PollOption(){
                    Content="PollOption#1"
                },
                new PollOption(){
                    Content="PollOption#2"
                }
            }
        };

        GetSession.Save(poll);

        return Content("Added");
    }

    [Transaction]
    public ActionResult Removed() {

        var poll = GetSession.Query<Poll>().FirstOrDefault();

        poll.PollOptions.RemoveAt(0);

        GetSession.Update(poll);

        return Content("Updated");
    }

when the remove action fired it not deleting polloption from db instead it set null in my foreign key :(

polloption table

ps. google not helped

Upvotes: 0

Views: 541

Answers (1)

cremor
cremor

Reputation: 6865

Cascade.All() only deletes the child object if the parent is deleted. If you want the childs to get deleted when they are removed from the collection, you need Cascade.AllDeleteOrphan().

Additional note: You also have to mark one side of your bidirectional association as Inverse(). More info about that here: http://nhibernate.info/doc/nh/en/index.html#collections-bidirectional

Upvotes: 1

Related Questions