c# - 从.net core中的layout.cshtml访问数据库

标签 c# .net asp.net-core

我在这样的模型中有一组用户:

[Key]
        [Required]
        public int ID { get; set; }

        [ForeignKey("Employee")]
        public int? EmployeeID  { get; set; }

        public int? CompanyID { get; set; }

        public string UserID { get; set; }

        [DataType(DataType.Text)]
        public string Firstname { get; set; }

        [DataType(DataType.Text)]
        public string Middlenames { get; set; }

        [DataType(DataType.Text)]
        public string Lastname { get; set; }

        [DataType(DataType.Text)]
        public string Address { get; set; }

        [DataType(DataType.Text)]
        public string Postnumber { get; set; }

        [DataType(DataType.Text)]
        public string City { get; set; }

        [DataType(DataType.Text)]
        public string Phone { get; set; }

        [DataType(DataType.EmailAddress)]
        [Required]
        public string Email { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime CreatedDate { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime EditedDate { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime CurrentLoginTime { get; set; }

        [DataType(DataType.DateTime)]
        public DateTime LastLoginTime { get; set; }

        public virtual Employee Employee { get; set; }

        public virtual Company Company { get; set; }

我想要做的是根据companyID是否有值在我的布局文件中显示一个菜单项。

在 MVC5 中我可以立即做到这一点,但在 .net core 中我不知道如何继续或搜索什么。

我希望这里有人能告诉我,这是如何工作的以及我应该如何做:-)

最佳答案

您在这里可以做的是创建一些服务(并将其注册到 DI 容器),该服务有办法确定您的情况。然后,您可以将该服务注入(inject)到您的 View 中并调用其方法来检查值:

@inject MyUserService myUserService
@if (await myUserService.GetIsCompanyOwnerAsync(User))
{
    <div>Item for company owner</div>
}

在您的服务中,您可以例如注入(inject)您的数据库上下文并根据当前用户查询用户:

public class MyUserService
{
    private readonly UserManager<User> _userManager;
    public MyUserService(UserManager<User> userManager)
    {
        _userManager = userManager;
    }

    public async Task<bool> GetIsCompanyOwnerAsync(ClaimsPrincipal user)
    {
        var user = await _userManager.GetUserAsync(user);
        return user.CompanyID.HasValue;
    }
}

请注意,这将导致对每个请求进行数据库查询,以便在布局中呈现该请求。从长远来看,最好将此属性(property)直接公开为对 claim 本金的 claim ,例如作为 OwnsCompany 声明。这样,您就可以直接在 View 中检查声明:

@if (await User.FindFirst("OwnsCompany") != null)
{
    <div>Item for company owner</div>
}

关于c# - 从.net core中的layout.cshtml访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52535512/

相关文章:

c# - Entity Framework Core DbUpdateException 详细信息

c# - LINQ - 对特定类型的类进行分组

c# - 必须将 GridView 添加到表单标签中进行渲染

c# - 如何在 vNext 中获取 SignalR 端点列表?

razor - ASP.NET Core - 像 MVC 一样的脚手架标识

c# - 如何选择正确的 Microsoft.AspNetCore.Authentication 替代方案

c# - C# 和 java 哪个更好?

java - 在 Xamarin.Android 中加载 .so 文件

c# - 如何测试函数返回 IEnumerable<Integer>

c# - Silverlight 3 WCF 服务 `CommunicationException` 服务器返回错误 : NotFound