NHibernate和HasMany映射

时间:2011-04-18 11:02:20

标签: asp.net-mvc nhibernate fluent-nhibernate mapping

我有两个实体的简单映射:poll和polloption

民意测验:

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

在测试代码中我试图删除第一个poll实体的民意调查实体

测试代码:

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

当remove动作触发它没有从db中删除polloption而不是在我的外键中设置null:(

polloption table

PS。谷歌没有帮助

1 个答案:

答案 0 :(得分:1)

如果父项被删除,

Cascade.All()仅删除子对象。如果您希望在从集合中删除子项时将其删除,则需要Cascade.AllDeleteOrphan()

附加说明:您还必须将双向关联的一侧标记为Inverse()。有关此处的更多信息:http://nhibernate.info/doc/nh/en/index.html#collections-bidirectional