简体   繁体   English

在Linq-to-SQL中从数据库读取数据

[英]Reading data from database in Linq-to-SQL

I have this class: 我有这个课:

public class Student1
{
            public String Name { set; get; }
            public String Number { set; get; }

            public List<String> TakedCourses  { set; get; }

            public List<String> PassedCourses = new List<String>();
}

and I use Linq-to-SQL to save students to the database. 我使用Linq-to-SQL将学生保存到数据库中。

Now I want to search a name in database and add all properties of this student to a new object of Student . 现在,我想在数据库中搜索一个名称,并将该学生的所有属性添加到Student的新对象中。

Like this: 像这样:

Student s = new Student();
s = d.Students.Where(c => c.Name == cobStudents.SelectedItem.ToString()).Select(c => c);

it doesn't work and I don't know ho do this. 它不起作用,我不知道该怎么做。

Thanks 谢谢

Use FirstOrDefault it returns first matching element, Where returns all matching students collection ( not single element). 使用FirstOrDefault它将返回第一个匹配的元素,其中返回所有匹配的学生集合 (而不是单个元素)。

Student s = new Student(); 
s = d.Students.FirstOrDefault(c => c.Name
== cobStudents.SelectedItem.ToString());

You can even use SingleOrDefault if you are sure that condition true for only one element. 如果您确定只有一个元素为true,则甚至可以使用SingleOrDefault

s = d.Students.SingleOrDefault(c => c.Name
== cobStudents.SelectedItem.ToString());

And then you could access using... 然后您可以使用...访问

if(s!= null)
{
       // access s here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM