【问题标题】:mvc join by using models objects使用模型对象进行 mvc 连接
【发布时间】:2019-10-10 17:12:36
【问题描述】:

我有以下架构:

public class Provider
    {

        [Key]
        public int ProviderId { get; set; }
        [ForeignKey("ProviderId")]
        public ApplicationUser User;

        public ICollection<ServiceProvider> Services { get; set; }
    }

public class ApplicationUser : IdentityUser
{
    public ApplicationUser() : base() { }

    public string Name { get; set; }
    public string Address { get; set; }
    public string Photo { get; set; }
    public string BusinessName { get; set; }
}

在我的后端,我有一封电子邮件作为输入,我正在尝试检查是否有任何提供该电子邮件的提供商。 我尝试使用以下代码:

if (context.Provider.Any(o => o.User.Email == input_mail) == false)

但我得到了一个空指针异常..

我知道我可以使用linku语法:

    var q = from au in _context.ApplicationUser
            join p in _context.Provider on au.Id equals p.ProviderId
            where au.Email=input_mail;

使用模型上下文有什么方法吗?而不是链接

【问题讨论】:

    标签: c# database mvcc


    【解决方案1】:

    如果我理解您的问题,那么以下句子就足够了,无需添加 FALSE if (context.Provider.Any(o => o.User.Email == input_mail))

    【讨论】:

    • 当我尝试在这部分访问用户时出现空指针异常
    【解决方案2】:

    覆盖电子邮件并在模型中测试它是否为空。

    // Override auto-implemented property with ordinary property
       // to provide specialized accessor behavior.
        public override string Email
        {
            get
            {
                return email;//declare this private string also in model
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    name = value;
                }
                else
                {
                    email= "Unknown";
                }
            }
        } 
    

    【讨论】:

    • 你说 input_mail 不为空,我说 o.User.Email 为空。另一种选择是使用 foreach 而不是 any()。或者也使用 Where 并检查返回的列表是否为 count 0
    • 问题是User为null,我尝试使用o.User.Email还是o.User.Name都没关系。它无法获取用户,因为它需要加入 IdentityUser 表
    • 试试o.User?.Email
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多