Skip to content

How do I map a Database View? #4561

@gdoron

Description

@gdoron

I have an hierarchy table that I'm trying to map with EF 7.
I tried almost everything (except probably the right thing) to map the view I already create in the DB but couldn't make it to work.

This is my model:

public class Post
{
    public int Id { get; set; }
    public string Text { get; set; }
    public DateTime PublishDate { get; set; }
    public DateTime? LastChangedDate { get; set; }
    public String UserId { get; set; }
    public ApplicationUser User { get; set; }
    public int ForumId { get; set; }
    public virtual Forum Forum { get; set; }
    public int? ReplyToPostId { get; set; }
    public Post ReplyToPost { get; set; }
    public virtual List<Post> Replies { get; set; }
}

And this is the view I'm trying to map:

CREATE VIEW HierarchyPosts 
as
WITH    cte ( Id, ParentPostId, Depth ) 
              AS ( SELECT   Id,
                            ReplyToPostId,
                            0 as TheLevel
                   FROM     posts
                   where ReplyToPostId is null
                   UNION ALL 
                   SELECT   pn.Id, 
                            pn.ReplyToPostId,
                            p1.Depth +1
                   FROM     Posts pn
                    INNER JOIN cte AS p1 on p1.Id = pn.ReplyToPostId
                 )
select cte.Id as PostId,ParentPostId, Depth, ForumId, LastChangedDate, PublishDate, ReplyToPostId, Text, U.UserName, u.Id as UserId
from  cte 
INNER JOIN POSTS P ON CTE.ID = P.ID
INNER JOIN USERS u ON U.id = p.UserId

What do I need to write in the DbContext to map HierarchyPosts?

BTW How do I write custom SQL as migration script, for stuff that EF currently doesn't support such as views or for stuff that EF will never support such as partitioning.

BTW2, it would be very helpful if EF 7 would finally be able the handle recursive data natively without requiring views or SP .

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions