Search code examples
linqentity-framework-core

EF Core : get random values ​from database


I have a parent table and a child table,I want to randomly receive 3 values ​​from each print ID in the child table and display them on the site.

Parent table:

Id       Name
---------------
1        Red
2        Blue 
3        Green

Child Table

Id   ColorId   Name
-----------------------
1       1      RedOne 
2       1      RedTwo
3       1      RedThree
4       2      BlueOne
5       2      BlueTwo
6       2      BlueThree

How can I do this?


Solution

  • You may try as below:

    Controller:
    public async Task<IActionResult> Index()
            {
                var colors =await  _context.Color.Include(x => x.colorChildren.OrderBy(y => Guid.NewGuid()).Take(3).OrderBy(y=>y.Id)).ToListAsync();
                //make a check before return View
                 ....
                return  View(colors);
                             
            }
    

    View:

    @model IEnumerable<Color>
    
    
    
    
    
    <table class="table">
        <thead>
            <tr>
                <th>
                    Colors
                </th>
                
            </tr>
        </thead>
        <tbody>
    @foreach (var item in Model) {
            <tr>
                <td>
                    @item.Name
                </td>   
            </tr>
            <tr>
                <td>
                        ChildColor
                </td>
                            
            </tr>
            <tr>
                    @foreach (var child in item.colorChildren)
                    {
    
                        <td>
                            @child.Name
                        </td>
    
    
                    }
            </tr>
                
    }
        </tbody>
    </table>
    

    Every time I refresh the page, diffrent childcolors would be displayed: enter image description here