ASP.NET Query Generics DBSet <t> </t>

时间:2012-08-22 11:36:21

标签: c# asp.net-mvc linq entity-framework generics

我正在尝试使用一个场景,我可以传入一个实体模型,并检查它是否有UserFK,如果它和当前用户不在管理员角色..检查UserFK是否匹配来自db ...的当前用户的UserId

我无法用泛型来计算最后一点..我认为我在正确的轨道上但不太确定..

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class IsOwnerAttribute<T> : AuthorizeAttribute where T : class
{
    public IsOwnerAttribute(IUnitOfWork context)
    {
        this.context = context;
    }

    public string RouteParameter
    {
        get { return this.routeParameter; }
        set { this.routeParameter = value; }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
        else if (IsOwner(filterContext))
        {
            return;
        }
        else
        {
            ViewDataDictionary viewData = new ViewDataDictionary();
            viewData.Add("Message", "You do not have sufficient privileges for this operation.");
            filterContext.Result = new ViewResult { ViewName = "Error", ViewData = viewData };
        }

    }

    bool IsOwner(AuthorizationContext filterContext)
    {
        bool result = false;

        int id = -1;
        if (filterContext.RouteData.Values.ContainsKey(this.RouteParameter))
        {
            id = Convert.ToInt32(filterContext.RouteData.Values[this.RouteParameter]);
        }

        var currentUser = Membership.GetUser();
        if (currentUser != null && !filterContext.HttpContext.User.IsInRole("Administrator"))
        {
            var userGuid = (Guid)currentUser.ProviderUserKey;

            // Stuck here.. trying to work out how with the Set<T> how i could then check if it has an Id property and a UserFK property and if it does then basically look up if the ID matches the ID in the route and the UserFK matches the userGuid then let them access the content...
            result = context.Set<T>().Where(c => c.Id == id && c.UserFK == userGuid).SingleOrDefault() != null;

        }

        return result;
    }

    string routeParameter = "id";
    readonly IUnitOfWork context;
    readonly IDbSet<T> dbset;
}

我不知道我是否以错误的方式思考它,或者是否有更好的方法,但我想知道什么是可能的......

1 个答案:

答案 0 :(得分:0)

为什么使用在哪里可以使用Find查找将搜索T主键的位置,并使用object作为参数。我认为这将解决你的问题。

示例更改此内容:

result = context.Set<T>().Where(c => c.Id == id && c.UserFK == userGuid).SingleOrDefault() != null;

用这个

result = context.Set<T>().Find(id);//and you don't need to filter also with user if your ID is primary key of the table 
相关问题