Entity Framework 6 code-first stored procedure map to complex objects

c# ef-code-first entity-framework-6 stored-procedures

Question

How can I retrieve a parent and its children using a saved procedure?

This is a generalised version of my code:

public class Parent
{
    public Int32 ParentId { get; set; }
    public Guid ParentGuid { get; set; }
    public String Name { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public Int32 ChildId { get; set; }
    public String Name { get; set; }
    public Int32 ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

public class ParentMapping : EntityTypeConfiguration<Parent>
{
    public ParentMapping()
    {
        ToTable("Parents");
        HasKey(t => t.ParentId);
    }
}

public class ChildMapping : EntityTypeConfiguration<Child>
{
    public ChildMapping()
    {
        ToTable("Children");
        HasKey(t => t.ChildId);
        HasRequired(t => t.Parent).WithMany(t => t.Children);
    }
}

I'm attempting to invoke a stored process and also get the parents' offspring:

_context.Database.SqlQuery<Parent>("EXEC [dbo].[GetParent] @ParentGuid", new SqlParameter("@ParentGuid", parentGuid)).SingleOrDefault();

The saved method is a straightforward select:

SELECT 
    P.*,
    C.*
FROM 
    [dbo].[Parents] P
INNER JOIN 
    [dbo].[Children] C ON C.[ParentId] = P.[ParentId]
WHERE 
    P.[ParentGuid] = @ParentGuid

Only the data from the Parent is now being mapped to the object. TheChildren collection has no items. What must I do in order to fill this?

1
0
3/12/2017 4:00:10 PM

Accepted Answer

ZZZ_tmp
1
3/7/2017 2:13:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow