using fluent nhibernate, is there anyway to have a private property mapped

后端 未结 3 432
心在旅途
心在旅途 2021-01-06 23:53

i have a field that i want to map as it links to a column in the database but i don\'t want any external class to access this field directly from my code (its only used in p

3条回答
  •  醉梦人生
    2021-01-07 00:16

    This an example from my project. My domain classes have only public properties. No setters. The object is created through the constructor and data is manipulated using methods.

    Entity

    public class User: Entity
    {
        private string _openid;
        private string _email;
        private string _username;
        private int roleid;
    
        // needed for mapping
        protected User() { }
    
        // your normal constructor
        public User(string openid)
        {
            Validator.NotNull(string openid, "openid is required.");
            _openid = openid;
        }
    
        public string Email
        {
            get { return _email; }
        }
    
        public string Username
        {
            get { return _username; }
        }
    
        public string Openid
        {
            get { return _openid; }
        }
    
       // Here are some methods
       // ... 
    }
    

    Mapping Class

    public class UserMap : ClassMap
        {
            public UserMap()
            {
                Table("user");
    
                // Reveal private attributes and map them
                Id(Reveal.Member("_id")).Column("id");
                Map(Reveal.Member("_username")).Column("username");
                Map(Reveal.Member("_openid")).Column("openid_claimed_identifier");
                Map(Reveal.Member("_email")).Column("email");
    
                // You need to create this mapping if you want to query using linq, 
                //see UserRepository below
                Map(x => x.Id, "id").ReadOnly();
                Map(x => x.Email, "email").ReadOnly();
                Map(x => x.Username, "username").ReadOnly();
                Map(x => x.Openid, "openid_claimed_identifier").ReadOnly();
            }
        }
    

    Repository

    public class UserRepository : Repository, IUserRepository
        {
            public UserRepository(ISession session)
               : base(session)
            {
            }
    
            public User find_user_by_openid(string openid_claimed)
            {
                return base.FindBy(x => x.Openid == openid_claimed);
            }
    
            public User find_user_by_id(int id)
            {
                return base.FindBy(x => x.Id == id);
            }        
    
        }
    

    One important thing to remember: do not use underscores within attribute names. Such as:

       public class User: Entity
        {
            //...
            private int role_id;
        }
    

    Fluent NHibernate does not like it when you use a particular attribute to map References.

提交回复
热议问题