fluent nhibernate - Many to Many mapping with attribute

后端 未结 2 990
南方客
南方客 2021-01-01 07:29

I have 2 master tables which are linked by a map table as below

User [UserId,Name]

Resource [ResourceId,Name]

UserResourceMap [UserId,ResourceId,AccessLeve         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 08:18

    As you've correctly identified in your database schema, this isn't a pure many-to-many relationship - it's two one-to-many relationships as the intermediate table has an attribute (the access level).

    I therefore think your domain is missing an entity - there doesn't appear to be any relationship in your model between a user and the resources they can access.

    How about something like this:

    public class User
    {
        public virtual int Id { get;protected set; }
        public virtual string Name { get;set; }
        public virtual ICollection UserResources { get; set;}
    }
    
    public class UserResource
    {
        public virtual int Id { get; protected set; }
        public virtual User User { get; set;}
        public virtual Resource Resource { get; set;}
        public virtual string AccessLevel { get; set;}
    }
    
    public class Resource
    {
        public virtual int Id { get;protected set; }
        public virtual string Name { get;set; }
    }
    

    And mappings like:

    public class UserMap : ClassMap
    {
        public UserMap()
        {
            Id(x => x.Id);
            Map(x => x.Name);
            HasMany(x => x.UserResource)
                .AsSet()
                .Inverse()
                .Cascade.AllDeleteOrphan();
        }
    }
    
    public class UserResourceMap : ClassMap
    {
        public UserResourceMap()
        {
            Table("UserResourceMap");
            Id(x => x.Id);
            References(x => x.User).Not.Nullable();
            References(x => x.Resource).Not.Nullable();
            Map(x => x.AccessLevel);
        }
    }
    
    public class ResourceMap : ClassMap
    {
        public ResourceMap()
        {
            Cache.ReadOnly();
    
            Id(x => x.Id);
            Map(x => x.Name);
        }
    }
    

提交回复
热议问题