EF Fluent API for hierarchical data

廉价感情. 提交于 2019-12-12 02:09:41

问题


I want to store hierarchical data in the database and need help how to configure the model. There is also a set of hierarchical data per user. After the data has been stored in the database, it is changed very rarely.

The database, I plan to use are as follows:

User
    Id          int


TreeEntity
    Id          int
    UserId      int
    ParentId    int

TreeEntity.UserId reference to User.Id TreeEntity.ParentId reference to TreeEntity.Id. If ParentId is unset, it is the root in the tree.

I've thought about trying to configure EF so that the data is mapped to the following classes

User
    // All TreeEntity that have TreeEntity.UserId==User.Id
    // Desirable, but not necessary
    //   ICollection<TreeEntity>        AllEntitiesForUser{get; set;}

    // The roots of the tree for this User. 
    // All TreeEntity that have TreeEntity.UserId==User.Id and TreeEntity.Parent==0
    ICollection<TreeEntity>     Tree {get;set;}

TreeEntity
    // Reference to the User 
    User                        User {get;set;}
    // Reference to the parent
    TreeEntity                  Parent {get;set;}
    // List of all children
    ICollection<TreeEntity>     Children {get;set;}

What I have succeeded so far are as follows

modelBuilder.Entity<User>()
    .HasMany(d => d.Tree)
    .WithRequired(d => d.User);

modelBuilder.Entity<TreeEntity>()
    .HasMany(d => d.Children)
    .WithOptional(d => d.Parent);

This is obviously not correct, but I do not really know how I should proceed. If that's even possible?

来源:https://stackoverflow.com/questions/35554821/ef-fluent-api-for-hierarchical-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!