Cannot use NHibernate Code Mapping for a private field

前端 未结 2 601
[愿得一人]
[愿得一人] 2021-01-27 23:36

What is the equivalent NHibernate Code Mapping for the following Fluent NHibernate code:

Map(x => x.Orders).Access.CamelCaseField(Prefix.Underscore);
<         


        
相关标签:
2条回答
  • 2021-01-28 00:20

    You have a couple of options to map a non-visible field by code.

    Here are some, please note that I haven't tested them yet as written, but should help you anyways:

    // Option 1:
    public class CustomerMap : ClassMapping<Customer>
    {
        public CustomerMap()
        {
            // ...
    
            Bag<Order>("_orders", collectionMapping =>
            {
                //...
            },
            map => map.ManyToMany(p => p.Column("OrderId")));
        }
    }
    
    // Option 2: No strings, but I'm not sure if this one would really work as is.
    public class CustomerMap : ClassMapping<Customer>
    {
        public CustomerMap()
        {
            // ...
    
            Bag(x => x.Orders, collectionMapping =>
            {
                collectionMapping.Access(Accessor.Field),
    
                //...
            },
            map => map.ManyToMany(p => p.Column("OrderId")));
        }
    }
    
    // Option 3: No strings, but more convoluted.
    public class Customer
    {
        internal class PrivatePropertyAccessors
        {
            public static Expression<Func<Customer, IEnumerable<Order>>> OrdersProperty = c => c._orders;
        }
    
        private readonly IList<Order> _orders = new List<Order>();
    
        public IEnumerable<Order> Orders
        {
            get { foreach (var order in _orders) yield return order; }
        }
    }
    
    public class CustomerMap : ClassMapping<Customer>
    {
        public CustomerMap()
        {
            // ...
    
            Bag(Customer.PrivatePropertyAccessors.OrdersProperty, collectionMapping =>
            {
                //...
            },
            map => map.ManyToMany(p => p.Column("OrderId")));
        }
    }
    
    0 讨论(0)
  • 2021-01-28 00:23

    You can just use a naming strategy:

    cfg.SetNamingStrategy(myStrategy);
    

    Where myStrategy is an implementation of INamingStrategy. See my blog post at https://weblogs.asp.net/ricardoperes/nhibernate-conventions

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