0

I am trying to search DB using LINQ to SQL and display it. I tried below code but it not showing record matching to criteria on console.

Here Details is table name

Detail detail = new Detail();

    Console.Write("\nEnter ID to Search Record :");
     int id = Convert.ToInt32(Console.ReadLine());
     var searchbyId = from search in db.Details
                         where search.Id == id
                         select search;
     db.SubmitChanges();
     Console.WriteLine("\n Search Results \n");
     Console.WriteLine(String.Format("Id \t | Name \t | Last Name \n"));

     Console.WriteLine(String.Format("{0} \t | {1} \t | {2} ",
                               detail.Id,detail.Name, detail.LastName));

Newbie trying to learn LINQ

6
  • What's detail here? Commented Jan 19, 2015 at 6:56
  • 2
    Why a SubmitChanges ? You don't update anything in db. Commented Jan 19, 2015 at 6:57
  • 1
    what's up with db.SubmitChanges();? Commented Jan 19, 2015 at 6:57
  • 1
    you never used searchbyId object aftre assign the value Commented Jan 19, 2015 at 6:57
  • Just a newbie trying to learn LINQ Commented Jan 19, 2015 at 6:58

2 Answers 2

2

There may be Multiple Results having Same ID so Use foreach

Console.Write("\nEnter ID to Search Record :");
 int id = Convert.ToInt32(Console.ReadLine());
 var searchbyId = from search in db.Details
                     where search.Id == id
                     select search;

 Console.WriteLine("\n Search Results \n");
 Console.WriteLine(String.Format("Id \t | Name \t | Last Name \n"));

 foreach(var item in searchbyId )
 Console.WriteLine(String.Format("{0} \t | {1} \t | {2} ",
                           item.Id,detail.Name, item.LastName));

101 LINQ Samples

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It worked perfectly. Will accept it as answer soon
@Richa try 101 LINQ Samples those are best from MSDN
0

I would try something like that:

Console.Write("\nEnter First Name :");
string id = Convert.ToInt32(Console.ReadLine());
var searchbyId = from search in db.Details
                 where search.Id == id
                 select search;
Console.WriteLine("\n Search Results \n");
Console.WriteLine(String.Format("Id \t | Name \t | Last Name \n"));

foreach(var item in searchbyId )
Console.WriteLine(String.Format("{0} \t | {1} \t | {2} ",
                       searchbyId.Id,detail.Name, searchbyId.LastName));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.