开发者

Entity Framework and self-referencing table

I nee开发者_运维百科d to have a database that starts with a table called "User" that needs to self reference itself and will have a very deep graph of related objects. It will need to be like the left side of the image below (disregard the right side).

Entity Framework and self-referencing table

I will also need to traverse through this graph both up and downwards in order to calculate percentages, totals, etc. In other words I'll need to travese the entire graph in some cases.

Is this possible and/or how is it done? Can traversing be done right in the LINQ statement? Examples?

EDIT: I'm basically trying to create a network marketing scenario and need to calculate each persons earnings.

Examples:

  1. To be able to calulate the total sales for each user under a specific user (so each user would have some sort of revenue coming in).
  2. Calculate the commission at a certain level of the tree (e.g. if the top person had 3 people below them each selling a product for $1 and the commission was 50% then there would be $1.50.)
  3. If I queried the image above (on the left) for "B" I should get "B,H,I,J,N,O"

Hopefully that helps :S


You can't traverse the whole tree using just LINQ in a way that would translate to single SQL query (or a constant count of them). You can do it either with one query for each level or with one query, that is limited to a specific count of levels (but such a query would get really big with many levels).

In T-SQL (I assume you're using MS SQL Server), you can do this using recursive common table expressions. It should be possible to put that into a stored procedure that you can use from LINQ to get the information you actually want.

To sum up, your options are:

  1. Don't use LINQ, just SQL with recursive CTE
  2. Use recursive CTE in a stored procedure from LINQ
  3. Use LINQ, creating one query for each level
  4. Use ugly LINQ query limited to just a few levels


I know this is late, but if you look at Directed Graph algorithms, you can bypass the recursive issues. check out these 2 articles:

http://www.sitepoint.com/hierarchical-data-database/

http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜