你能告诉我我的实体框架查询有什么问题吗?

时间:2013-01-12 22:07:59

标签: c# entity-framework

我正在尝试使用C#中的此代码选择Member类型的实体。我正在观看视频教程,他们也是这样做的,但它对我不起作用。

        Member member = new Member();
        var query =  from m in db.Members  where Member.MemberID == textBox1.Text 
        select m;     
        var currentMember =  query.FirstOrDefault();
        string CurrentID = M.MemberID;    

没有例外或东西,但我得到所有currentMember的属性为null。 任何获得预期结果的想法?

2 个答案:

答案 0 :(得分:1)

我想你可能会在这里混淆你的变量。让我们尝试清理这段代码:

var memberQuery = from m in db.Members
                  where m.MemberID == textBox1.Text
                     // ^ you need to reference the MemberID by the query
                     //   variable (m) not the class name (Member).
                  select m;

var member = memberQuery.SingleOrDefault();
                      // ^ when you only expect zero or one records from the
                      //   database, use SingleOrDefault instead of
                      //   FirstOrDefault, because it will throw an exception
                      //   when more than one record is returned.

if (member != null)
 // ^ always check to make sure that the database returned a value before trying
 //   to access any fields on the object.
{
    string currentId = member.MemberID;
}
else
{
    // a member with the given ID doesn't exist in the database
}

答案 1 :(得分:0)

问题出在where Member.MemberID == textBox1.Text

应该是where m.MemberID == textBox1.Text

您为什么要创建会员? Member member = new Member();

只需从查询中获取成员并从中获取ID。