开发者

How do I store role<->permission in the cache for best result?

开发者 https://www.devze.com 2023-02-14 06:07 出处:网络
I have a table in the DB with two columns, roles a开发者_开发知识库nd permissions that looks like this:

I have a table in the DB with two columns, roles a开发者_开发知识库nd permissions that looks like this:

role - permission

user - addItem

admin - removeItem

admin - advancedSearch

guest - simpleSearch

user - editItem

manager - editUser

...etc.

I need to store these in the .net's cache so that I can check if a permission exists for a specific role.

(Here's the psuedo-code)

if ("permission" is in Cache["role"]) // Authorize access

But how do I add and store them in the Cache for best result?

In PHP I'd do something like this I guess:

array ( "user"  => array ( "addItem", "editItem"),
        "admin"  => array ( "removeItem", "advancedSearch"),
         ....

Is there an equivalent or better/faster way in C#?

Thanks!

/Niklas


Maybe something like a Dictionary<string, HashSet<string>>?

For example:

var pairs = new[] { 
    new{Role="user",Permission="addItem"},
    new{Role="admin",Permission="removeItem"},
    new{Role="admin",Permission="advancedSearch"},
    new{Role="guest",Permission="simpleSearch"},
    new{Role="user",Permission="addItem"},
    new{Role="manager",Permission="editUser"},
};
Dictionary<string, HashSet<string>> cache = pairs.GroupBy(pair => pair.Role)
    .ToDictionary(grp => grp.Key, grp => new HashSet<string>(
          grp.Select(g => g.Permission)));
cache["user"].Contains("addItem");

Or if reading from a data-reader (comment):

var cache = new Dictionary<string, HashSet<string>>();
using (var reader = GetReader()) {
    while (reader.Read()){
        string role = reader.GetString(0),
            permission = reader.GetString(1);
        HashSet<string> permissions;
        if (!cache.TryGetValue(role, out permissions)){
            cache.Add(role, permissions = new HashSet<string>());
        }
        permissions.Add(permission);
    }
}


Building on Marcs answer, you can use collection initializers directly inline:

var cache = new Dictionary<string, HashSet<string>>()
    {
        { "user", new HashSet<string>() { "addItem" } },
        { "admin", new HashSet<string>() { "removeItem", "advancedSearch" } },
        { "guest", new HashSet<string>() { "simpleSearch" } }
    };

Looks a little bit cleaner than the LINQ version, and should be relatively familiar to you with a background in PHP since the syntax is quite similar.

0

精彩评论

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