Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架用父对象加载子对象_C#_Entity Framework - Fatal编程技术网

C# 实体框架用父对象加载子对象

C# 实体框架用父对象加载子对象,c#,entity-framework,C#,Entity Framework,这目前对我有效,但我不想在加入后手动将子项分配给父项 有更好的方法吗?我想使用同样的语法风格 如何在不必手动将子对象分配给父对象的情况下完成此操作 谢谢 只要写: public Parent Get(int parentId) { var result = this.dbContext.Parents .Join( this.dbContext.Childs, p => p.Id, c

这目前对我有效,但我不想在加入后手动将子项分配给父项

  • 有更好的方法吗?我想使用同样的语法风格
  • 如何在不必手动将子对象分配给父对象的情况下完成此操作
  • 谢谢

    只要写:

    public Parent Get(int parentId) {
        var result = this.dbContext.Parents
             .Join(
                 this.dbContext.Childs,
                 p => p.Id,
                 c => c.ParentId,
                 (p, c) => new { Parent = p, Child = c })
                 .AsNoTracking().Where(m => m.Parent.Id == parentId)
                 .FirstOrDefault()
    
        result.Parent.Child = result.Child;
        return result.Parent;
    }
    
    结果将包含相应的child

    包括

    var result = this.dbContext.Parents.Where(m => m.Parent.Id == parentId)
         .Include(p=>p.Child).FirstOrDefault()
    
    父亲班

    FatherRepository.All().Including(x => x.Childs, x => x.Childs.Select(y => y.ChildChild));
    
    儿童班

    public class Father
    {
        public int Id { get; set; }
    
        #region Navigations Properties
        public virtual List<Child> Childs { get; set; }
        #endregion
    }
    
    public class Child
    {
        public int Id { get; set; }
        public int ChildChildId { get; set; }
        public int FatherId { get; set; }
    
        #region Navigations Properties
        public virtual Father Father { get; set; }
        public virtual ChildChild ChildChild { get; set; }
        #endregion
    
    }
    

    我本来是这样做的,但是我得到了一个错误“无效列Child_Id”。。。父表中不存在子表的主键。父项的主键作为外键存在于子表中。是否可以尝试添加
    [ForeignKey(“ChildField”)]\n public int?Child_Id{get;set;}
    before
    public Child字段{get;set;}
    它不是先编码的。
    public class Child
    {
        public int Id { get; set; }
        public int ChildChildId { get; set; }
        public int FatherId { get; set; }
    
        #region Navigations Properties
        public virtual Father Father { get; set; }
        public virtual ChildChild ChildChild { get; set; }
        #endregion
    
    }
    
    public class ChildChild
    {
        public int Id { get; set; }
    }