简体   繁体   中英

C# : how to declare a variable for an entity table?

I'm using C# Entity Framework to select records from a database table. Based on selection criteria, I will use different select statements.

    if ( condition1 )
    {
        var records = _context.Member.Select( .... )
    }
    else if (condition2)
    {
        var records = _context.Member.Select( .....)
    }......

And then, I need to make some decisions depending on whether there are records and process those records.

    if (records != null)
    {

    }
    else if (....)

The compiler complains that "records" does not exist in the current context . I think the reason why this happens is that records is declared in a if block. I don't want to do the 2nd step inside the if block because the processing is the same and it quite lengthy.

I've tried declaring record outside the block first, but I don't know what Type to use. So how do I declare a variable to hold the records return from Entity Framework?

Thanks.

What data type is records? Find that out and lets call that T. If you are using Visual Studio, just hover over the Select method. It will popup some information about method, there is also a return type before the name of the method.

Then write this code:

T records = null; // or some kind of empty collection

if ( condition1 )
{
    records = _context.Member.Select( .... )
}
else if (condition2)
{
    records = _context.Member.Select( .....)
}

The reason you ran in to this problem is that 'records' is defined only in the scope of '{}' curly braces. By bringing it up like i showed you, you move it to the same context where you have the decisions

if (records != null)
{

}
else if (....)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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