简体   繁体   中英

ASP.NET MVC get specific columns from table in EF

I have a table with below columns.

CREATE TABLE [dbo].[tbl_QuizQue](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [question] [nvarchar](max) NOT NULL,
    [opt1] [nvarchar](50) NOT NULL,
    [opt2] [nvarchar](50) NOT NULL,
    [opt3] [nvarchar](50) NOT NULL,
    [ans] [nvarchar](50) NOT NULL
    )

I am trying to get a random record from this table, but only specific columns Like id, question, opt1, opt2, opt3. Present I am getting random record but it is fetching all columns. I tried below code for fetching a record with specific columns

dbUserEntities obj = new dbUserEntities();
    // GET api/values
    public IEnumerable<tbl_QuizQue> Get()
    {
        var result = obj.tbl_QuizQue.OrderBy(r => Guid.NewGuid()).Select(o => new { o.id, o.question, o.opt1, o.opt2, o.opt3 });
        return result;
        }

Here, i am getting below error while return result;

Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 
        'System.Collections.Generic.IEnumerable<studentQuiz.tbl_QuizQue>'. An explicit conversion exists (are you missing a cast?)

Help me where I am doing wrong.

I'd do this:

public IEnumerable<tbl_QuizQue> Get()
{
    var result = obj.tbl_QuizQue.OrderBy(r => Guid.NewGuid())
        .Select(o => new { o.id, o.question, o.opt1, o.opt2, o.opt3 })
        .AsEnumerable()
        .Select(q => new tblQuizQue {q.id, q.question, q.opt1, q.opt2, q.opt3);
    return result;
}

By first getting back just the columns you are interested in, you can constrain the query. You can then map them into the object you are interested in.

Change the return type of the Get function to

IEnumerable<dynamic>

and your code will execute.

As for whether it's a good idea, I guess you have to defer to the customs of the c# tribe.

I'd be tempted to use it all the time.

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