开发者

Fluent NHibernate has many mapping where child table has not primary key

So I'm a couple of weeks into NHibernate so pleae bear with me. I am working on a legacy database with lots of weird issues.

I have a name object

public class Name    {    
        public Name()
        {
            Addresses = new List<Address>();
        }    
        public virtual string Id { get; set; }
        public virtual string FirstName { get; set; }    
        public virtual string LastName { get; set; }     
        public virtual IList<NameAddress> Addresses { get; set; }    
}

It has children of address

public class Address 
{
        public virtual string NameId { get; set; }
        public virtual string Line1 { get; set; }
        public virtual string City { get; set; }
        public virtual string State { get; set; }
        public virtual string Zipcode { get; set; }
        public virtual string Type { get; set; }
        public virtual bool IsPreferrred { get; set; }
}

Here are the mappings Address has no primary key defined but it is name_id and type that make it unique. The columns you see are the table structure.

   Table("ADDRESS");
    CompositeId()
            .KeyProperty(x => x.NameId, "NAME_ID")
            .KeyProperty(x => x.Type, "ADDRESS_TYPE");
    Map(x => x.开发者_如何学编程IsPreferred)
        .Column("PREF");
    Map(x => x.Line1)
        .Column("ADDRESS1");
    Map(x => x.Line2)
        .Column("ADDRESS2");
    Map(x => x.City)
        .Column("CITY");
    Map(x => x.State)
        .Column("STATE");

Name Table("NAME");

        Id(x => x.Id)
            .GeneratedBy.Custom<XXIdentifierGenerator>(p => p.AddParam("prefix", "NAME"))
            .Column("NAME_ID");
        Map(x => x.Prefix)               
            .Column("NAME_PRE");
        Map(x => x.FirstName)
            .Column("NAME_FIRST");
        HasMany(x => x.Addresses)
            .KeyColumn("NAME_ID")
            .Table("ADDRESS")
            .LazyLoad();

I can create a name without any addresss and get the generated id back.

 repository.Save(name); // only calls session.Save and does a commit 
 Address address = new NameAddress {IsPreferred = true, Type= "Home", Line1 = "123 Main St",
                                    City = "Anytown", State = "CT", Zipcode="06512" };
 name.Addresses.Add(address);
 repository.SaveOrUpdate(name);

When I try to save the address I get an exception

     {"Unexpected row count: 0; expected: 1"}

I am not sure if

  1. My mapping is wrong
  2. I don't get how to wire up a has many
  3. I can't do this without a primary key
  4. In this case do the addresses have to be saved on their own?

Thanks, Paul


This is a bit of a shot in the dark, but how about adding .Cascade.All or similar on the HasMany(x => x.Addresses) mapping for Name?

I would imagine that NHibernate needs to know that you want new Addresses to be inserted along with a new Name.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜