【问题标题】:ASP.net MVC: Display Results For A Specific UserASP.net MVC:显示特定用户的结果
【发布时间】:2017-06-12 01:19:14
【问题描述】:

我正在使用带有个人用户帐户的 ASP.net MVC。我想要一个显示所有数据库记录的页面,其中“用户”字段等于帐户的电子邮件地址。我使用脚手架来创建所有内容,我只需要以某种方式添加一个仅显示特定用户记录的 where 子句。我在下面的控制器中尝试过。它编译,并且 Exhibit5/Index/ 按预期提示用户登录屏幕。但是,在单击登录时,我得到一个找不到网络路径的错误。

型号:

public partial class Exhibit5
{
    public int ID { get; set; }
    public string User { get; set; }
    public string Name { get; set; }
    public Nullable<int> EmployeeID { get; set; }
    public string ProposedTitle { get; set; }
    public string Department { get; set; }
    public Nullable<decimal> AnnualizedSalary { get; set; }
    public string PayGrade { get; set; }
    public Nullable<decimal> MktPay { get; set; }
    public Nullable<decimal> RangeMin { get; set; }
    public Nullable<decimal> RangeMid { get; set; }
    public Nullable<decimal> RangeMax { get; set; }
    public Nullable<decimal> RangePen { get; set; }
    public Nullable<decimal> CompaRatio { get; set; }
    public Nullable<decimal> BelowMin { get; set; }
    public Nullable<decimal> AboveMax { get; set; }
}

}

控制器:

public class Exhibit5Controller : Controller
    {
        private WebApplication1Context db = new WebApplication1Context();
        [Authorize]
        // GET: Exhibit5
        public ActionResult Index()
        {
            var ex5 = db.Exhibit5.Where(d => d.User == User.Identity.GetUserName()).ToList();
            return View(ex5);
        }

【问题讨论】:

  • 你调试代码了吗?它是否进入登录的发布操作?用户名和密码验证是否正确进行?
  • ^ 那。另外,Identity 是否真的为这个请求设置了?另外,您确定为此操作创建了视图吗?
  • 在调试中,我现在收到以下错误: System.NotSupportedException: 'LINQ to Entities does not identify the method 'System.String GetUserId(System.Security.Principal.IIdentity)' 方法,和此方法无法转换为商店表达式。'
  • 我用这个解决了这个问题:stackoverflow.com/questions/37435109/… 谢谢!

标签: c# asp.net-mvc


【解决方案1】:

应该是:

var userName = User.Identity.GetUserName();
var ex5 = db.Exhibit5.Where(u => u.User == userName )
                         .Select(y => y.User);

【讨论】:

    【解决方案2】:

    快速修复:

    public ActionResult Index()
    {
       var userName = User.Identity.GetUserName();
       var ex5 = db.Exhibit5.Where(d => d.User == userName).ToList();
       return View(ex5);
    }
    

    User.Identity.GetUserName()Where 中不起作用的原因是Entity Framework 需要将您的Where 代码转换为SQL 查询并且它不知道如何处理User.Identity.GetUserName()。通过将其拉出,Entity Framework 可以做到(有点):

    SELECT * FROM Exhibit5 WHERE User = <User Name>
    

    【讨论】:

      猜你喜欢
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      相关资源
      最近更新 更多