简体   繁体   English

ASP.NET MVC从EF中的表获取特定列

[英]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. 我正在尝试从此表中获取随机记录,但仅获取特定列,例如id,问题,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; 在这里,我在return result;时低于错误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 将Get函数的返回类型更改为

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. 至于是否是个好主意,我想您必须遵照c#部落的习惯。

I'd be tempted to use it all the time. 我很想一直使用它。

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

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