子集合未填充超过1个结果

时间:2018-07-15 21:23:49

标签: entity-framework-core ef-core-2.0 ef-core-2.1

我有一个模型,该模型的子集合仅返回第一条记录。 父(userModel)看起来像:

//start running timer in the HTML widget
var runningTimer = new Timer();
runningTimer.start({precision: 'seconds', startValues: {seconds: startSeconds}});
runningTimer.addEventListener('secondsUpdated', function (e) {
  $('#timerDiv').html(timerRun.getTimeValues().toString());
});

//attach event listener to page onDetach event to stop timer
widget.root.getElement().addEventListener("unload", function(){
    runningTimer.stop();
    console.log("Timer stopped");
)};

不能正确补水的模型是UserMember集合。 看起来像这样:

 public class User
{

    [Key]
    public int UserID { get; set; }
    public string Username { get; set; }
    [StringLength(50)]
    public string EmailAddress { get; set; }
    public bool IsDeleted{ get; set; }
    [ForeignKey("UserID")]
    public virtual UserInformation UserInformation{ get; set; }
    [ForeignKey("UserID")]
    public virtual IEnumerable<UserMember> UserMember{ get; set; }

}

我正在使用的查询是:

 public class UserMember
{
    [Key]
    public int UserID { get; set; }
    public int GroupID { get; set; }
    public DateTimeOffset Created { get; set; }
    public virtual Group Group { get; set; }
}

它正在给一个UserMember补水,但是我希望看到3个结果。 用户-> UserMember。

我尝试将IEnumerable更改为ICollection,但它也不起作用。 除了通常的映射等之外,我在上下文中没有任何流畅的语法代码-modelBuilder.Entity()。ToTable(“ user”,“ info”);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您没有正确映射外键。您的模型类应如下所示:

public class User
{

    [Key]
    public int UserID { get; set; }
    public string Username { get; set; }
    [StringLength(50)]
    public string EmailAddress { get; set; }
    public bool IsDeleted{ get; set; }

    public virtual UserInformation UserInformation{ get; set; }

    public virtual ICollection<UserMember> UserMembers { get; set; }

}

public class UserMember
{
    [Key]
    [ForeignKey("User")]
    public int UserID { get; set; }
    public int GroupID { get; set; }
    public DateTimeOffset Created { get; set; }
    public virtual Group Group { get; set; }

    public virtual User User {get; set;}
}

然后您的查询应如下:

public IQueryable<User> GetUserByUserSId(Guid userId)
{
        return _freightPortalPreferencesContext.User
                .Include(u => u.UserInformation)
                .Include(u => u.UserMembers)
                .Where(u => u.SID == userId && u.Enabled).AsQueryable();

}