开发者

Fluent NHibnerate Domain mapping issue

My Domain:

public class Person
{
    public Person() { }
    public virtual int PersonId { get; set; }
    public virtual string Title { get; set; }
    public virtual string FirstName { get; set; }
    public virtual IList<Address> Addresses { get; set; }
}
public class Address
{
    public Address()
    {}
    public virtual int AddressId { get; set; }
    public virtual Person AddressPerson { get; set; }
    public virtual string BuildingNumber { get; set; }
    public virtual string AddressLine1 { get; set; }
}

My Mapping:

public class AddressMap : ClassMap<Address>
{
    public AddressMap()
    {
        Table("Address");
        LazyLoad();
        Id(x => x.AddressId).GeneratedBy.Identity();
        References(x => x.AddressPerson).Column("PersonId").Not.Nullable();
        Map(x => x.BuildingNumber).Length(250).Not.Nullable();
        Map(x => x.AddressLine1).Length(100).Not.Nullable();
    }
}

public class PersonMap : ClassMap<Person>
{
   public PersonMap()
   {
    Table("Person");
    LazyLoad();
    Id(x => x.PersonId).Column("PersonId").GeneratedBy.Identity();
    Map(x => x.Title).Length(6).Nullable();
    Map(x => x.FirstName).Length(100).Not.Nullable();
    HasMany(x => x.Addre开发者_运维知识库sses).KeyColumn("PersonId");
    HasMany(x => x.Applications).KeyColumn("PersonId");
   }
}

So when I attempt to add an address to the person list and save I get the following error:

object references an unsaved transient instance - save the transient instance before flushing. Type: Rise.Core.Domain.Address, Entity: Rise.Core.Domain.Address

I am new to NHibernate and I am a little confused as to what exactly is going on. I beleive I need to Create a BiDirectional attribute Or should I just be saving the address myself after I have saved the person ID session.SaveOrUpdate(Person) and then session.SaveOrUpdate(Address)? Not sure what exactly I am doing wrong, I do like having the list of address on Person that can be lazy loaded as it makes it really easy to write some Linq.

Any suggestions?


I believe the error came up since you tried to save an Address before saving the Person to whom it belonged.

I think you should

1) Save Person P with empty list of <IList> Addreses

2) Save Address A after adding this Person P as AddressPerson of A

3) Add Address A to <IList> Addresses of Person P


Found a post on stackoverflow about this! I just need to add

.KeyColumn("PersonId") .Inverse().Cascade.SaveUpdate();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜