我使用的是Asp.net 3.5和EF 4。
我需要在DataBase中找到一个特定的行,并在标签上显示单个值作为字符串。
目前我使用此代码,它正在工作,所以我找到一个Object并读取它的属性。
var myAuthor = (from at in context.CmsAuthors
where at.AuthorId == myRow.AuthorId
select at).Single();
myAuthorNameLabel.Text = myAuthor.LastName;
我想知道:
答案 0 :(得分:4)
这是方法语法(使用lambdas)
myAuthorNameLabel.Text = context.CmsAuthors
.Where(at => at.AuthorId == myRow.AuthorId)
.Select(at => at.LastName)
.SingleOrDefault() ?? string.Empty;
答案 1 :(得分:3)
您可以使用:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);
实际上这会更好:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();
如何使用匿名类型的示例:
var myAuthorNames =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();