mapping nhibernate parent/child relationship the 'other' way round

后端 未结 3 2050
生来不讨喜
生来不讨喜 2021-01-22 10:50

using FluentNhibernate;

I am trying to persist a seemingly simple object model:

public class Product
{
    public int Id { get; set; }
    public string          


        
相关标签:
3条回答
  • 2021-01-22 11:01

    You are trying to map a one-to-one relationship as a one-to-many by mapping what would be the many side twice. That won't work. NHibernate is strict in its definition of one-to-one and requires that both sides have the same primary key, so that won't work either.

    I've butted heads with this before and the best workaround I found is to model it as a standard on-to-many but only allow one item in the collection by encapsulating access to the it. In your case I would guess that Product would be the one side and Config the many.

    0 讨论(0)
  • 2021-01-22 11:02

    I'm not sure if Config is used elsewhere but you could ignore ConfigId as its identity

    public class Config
    {
        public int Id { get; set; }
        public Product Product { get; set; }
        public string ConfigField1 { get; set; }
        public string ConfigField2 { get; set; }
    }
    
    public class ProductMap : ClassMap<Product>
    {
        public class ProductMap()
        {
            HasOne(p => p.Config);
        }
    }
    
    public class ConfigMap : ClassMap<Config>
    {
        public class ConfigMap()
        {
            Id(c => c.Id, "ProductId").GeneratedBy.Foreign("Product");
    
            References(c => c.Product, "ProductId");
            Map(c => ...);
        }
    }
    
    0 讨论(0)
  • 2021-01-22 11:21

    Another idea is to join and map as Component

    public class ProductMap : ClassMap<Product>
    {
        public class ProductMap()
        {
            Join("Config", join => 
            {
                join.KeyColumn("ProductId");
                join.Component(p => p.Config, c =>
                {
                    c.Map(...);
                });
            }
        }
    }
    

    Disadvantage is that you can not query Config directly, you have to query through Product

    0 讨论(0)
提交回复
热议问题