Linq offers to write queries against various data sources including c# code as same capabilities as SQL database. In this example we need to filter customer name with any letter and having orders. For customer name we can use startwith parameter function. Inorder to filter the customers having orders tables should have foreign key relation. It has already relation by the way we can get orders count. Belew example I will show you how to filter the record(s).
I used jQuery datatable for displaying records.
This example I used northwind sample database for more detail about how to download click link button it will show a popup.
Step 1: Create an ado.net entity data model using table customer and orders and generate entity for that.
Step 2: Right click on the "Controllers" folder and add "Home" controller. Copy and paste the following code. Please make sure to include "LinQTutoris.Models" namespace.
using LinQTutoris.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LinQTutoris.Controllers
{
public class HomeController : Controller
{
models db = new models();
public ActionResult Index()
{
var customerOrders = from customer in db.Customers
where customer.ContactName.StartsWith("C") && customer.Orders.Count > 0
orderby customer.ContactName
select customer;
return View(contactOrders);
}
}
}
Step 3: Right click on the "Index" action method in the "HomeController" and add "Index" view. Copy and paste the following code.
@model IEnumerable<LinQTutoris.Models.Customer>
@{
ViewBag.Title = "filter customer name start with C & having order using linq";
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script type="text/javascript">
$(document).ready(function () {
$('#example').DataTable();
});
</script>
<h2>filter customer name start with C& having order using linq</h2>
<table id="example">
<thead>
<tr>
<th>Contact Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
@foreach (var row in Model)
{
<tr>
<td>@row.ContactName</td>
<td>@row.Country</td>
</tr>
}
</tbody> </table>
Output:
Post your comments / questions
Recent Article
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
- Error: error:0308010C:digital envelope routines::unsupported
Related Article