0

我正在调用一个似乎无法正常工作的 linq 语句:

我的客户模型:

public class Client
{

    [UIHint("Hidden")]
    public int ClientId { get; set; }

    [UIHint("Hidden")]
    public int UserProfileId { get; set; }

    public int Age { get; set; }

    [UIHint("Hidden")]
    public int GenderId { get; set; }
    public string GenderDescription { get; set; }

    [UIHint("Hidden")]
    public int SettingId { get; set; }

    public virtual Gender Gender { get; set; }
    public virtual Setting Setting { get; set; }
    public virtual UserProfile UserProfile { get; set; }
}

我的 Linq 通话:

var clients = db.Clients.Include(c => c.Gender).Include(c => c.Setting).Include(c => c.UserProfile).OrderBy(c => c.ClientId);

这将使用基于 GenderId 和 SettingId 的正确信息填充 Gender 和 Setting 字段,但 UserProfile 不会。有没有合理的解释,还是我需要不断地用头撞桌子?

4

1 回答 1

0

我遇到的问题是,当我创建 UserProfile 模型时,我使用了 UserId 而不是 UserProfileId。框架一直在寻找一个不存在的 ID。

正确的模型应该如下所示:

public class UserProfile
{
    public UserProfile()
    {
        this.Casefiles = new HashSet<Casefile>();
    }

    [Display(Name="Author")]
    public string FullName
    {
        get { return LastName + ", " + FirstName; }
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserProfileId { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [EmailAddress]
    public string EmailAddress { get; set; }

    // UserInRole Level
    public string Role { get; set; }

    [Display(Name = "Request Account Uplevel to Contributor")]
    public bool RequestUplevel { get; set; }

    public virtual ICollection<Casefile> Casefiles { get; set; }

}

这样,当您拨打以下电话时:

var clients = db.Clients.Include(c => c.Gender)
                        .Include(c => c.Setting)
                        .Include(c => c.UserProfile)
                        .OrderBy(c => c.ClientId)
                        .Where(u => u.UserProfileId == WebSecurity.CurrentUserId);

这将返回客户端模型中的每个虚拟调用。

于 2013-09-09T14:25:24.050 回答