本文介绍了在NHibernate的子表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有NHibernate的任何方式,我可以使用下面的实体

Is there any way in NHibernate that I can use the following Entities

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Pet> Pets { get; set; }
}

public class Pet
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

和不必为了创建人是一个特殊的AddPet方法有孩子的宠物保存。

And not have to create a "special" AddPet method on Person in order to have Child pets saved.

public void AddPet(Pet p)
{
    p.Person = this;
    Pets.Add(p);
}

_session.SaveOrUpdate(person);



不保存的宠物,因为宠物有没有人参考。

Does not save the Pets because Pet has no Person reference.

如果我更新宠物包含此引用。

If I update Pets to contain this reference.

public class Pet
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Person Person { get; set; }
}

在新的宠物我还是要设置人,这似乎有点小题大做我也有风险,因为人们仍然可以调用

On new pets I still have to set Person this seems like overkill to me and also risky as People can still call

person.Pets.Add(new Pet())

我能想到的唯一的选择是一个自定义列表,添加子实体时,设置家长参考。

The only other option I can think of is a Custom list that sets the parent reference when adding child entities.

推荐答案

我修改你的例子只是一个位(符合这里的许多建议):

I modified your example just a bit (in line with many of the suggestions here):

public class Person
{
    private IList<Pet> pets;

    protected Person()
    {}

    public Person(string name)
    {
        Name = name;
        pets = new List<Pet>();
    }

    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IEnumerable<Pet> Pets
    {
        get { return pets; }
    }

    public virtual void AddPet(Pet pet)
    {
        pets.Add(pet);           
    }
}

public class Pet 
{
    protected Pet()
    {}

    public Pet(string name)
    {
        Name = name;
    }

    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
}

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id).GeneratedBy.GuidComb();
        Map(x => x.Name);
        HasMany(x => x.Pets).Cascade.AllDeleteOrphan().Access.AsLowerCaseField();
    }
}

public class PetMap : ClassMap<Pet>
{
    public PetMap()
    {
        Id(x => x.Id).GeneratedBy.GuidComb();
        Map(x => x.Name);
    }
}



下面的测试:

The following test:

    [Test]
    public void CanSaveAndRetrievePetAttachedToPerson()
    {
        Person person = new Person("Joe");
        person.AddPet(new Pet("Fido"));

        Session.Save(person);

        Person retrievedPerson = Session.Get<Person>(person.Id);
        Assert.AreEqual("Fido", retrievedPerson.Pets.First().Name);
    }



通行证。

passes.

请注意,这是使用功能NHibernate的映射和会话。

Note that this is using Fluent NHibernate for the mapping and the Session.

这篇关于在NHibernate的子表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:24