0

我很确定我在这段代码片段上是正确的,但我想要做的是在页面上显示一个特定的记录,它有一个导航控件,允许你转到下一个和上一个记录(修改版本在 MVC3 中生成的详细信息视图页面)。

当我导航到页面时,代码通过 ViewBag 变量初始化 ActionLink 按钮,并在相应控制器内的此方法中设置。

我的问题是,是否有更好的方法来执行以下操作,同时防止超出数据库记录范围的问题?

public ViewResult Details(int id)
{
    //Conditional Statements to manage navigation controls
    if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID < id))
    {
        //Set value next button
        ViewBag.NextID = id;

        ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID; //Inverted logic due to orderby
    }
    else if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID > id))
    {
        ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID; //Inverted logic due to orderby

        //Set value previous button
        ViewBag.PreviousID = id;
    }
    else
    {
        //Set value next button
        ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID;

        //Set value previous button
        ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID;
    }

    tblQuoteLog tblquotelog = db.tblQuoteLog.Find(id);

    return View(db.tblQuoteLog.Where(x => x.nID == id).FirstOrDefault());
}

编辑 我对我的逻辑进行了更改,这似乎从迈克给出的想法中可以正常工作(可能不整洁,但它更小)。

        //EOF is set to true if no records are found.
        var nextRecord = (from r in db.tblQuoteLog
                          orderby r.Quote_ID descending
                          where r.Quote_ID < id
                          select new
                          {
                              Quote_ID = r.Quote_ID,
                              EOF = false
                          }).Take(1).
                          FirstOrDefault() ?? new { Quote_ID = id, EOF = true };

        var previousRecord = (from r in db.tblQuoteLog
                              orderby r.Quote_ID ascending
                              where r.Quote_ID > id
                              select new
                              {
                                  Quote_ID = r.Quote_ID,
                                  EOF = false
                              }).Take(1).
                              FirstOrDefault() ?? new { Quote_ID = id, EOF = true };

        //Conditional Statements to manage navigation controls
        if ((nextRecord.EOF == true))
        {
            //Set value next button
            ViewBag.NextID = id;

            ViewBag.PreviousID = previousRecord.Quote_ID;
        }
        else if ((previousRecord.EOF == true))
        {
            ViewBag.NextID = nextRecord.Quote_ID;

            //Set value previous button
            ViewBag.PreviousID = id;
        }
        else
        {
            //Set value next button
            ViewBag.NextID = nextRecord.Quote_ID;

            //Set value previous button
            ViewBag.PreviousID = previousRecord.Quote_ID;
        }

现在使用匿名类型在 Linq 查询中进行错误检查。我使用 EOF(文件结尾)标志,以便在未找到记录时将 ID 设置为当前记录,并将 EOF 设置为 true。

感谢您的建议:)。

4

2 回答 2

0

从 id -1 中选择前 3 名怎么样?

    public ViewResult Details(int id)
{
    var items = db.tblQuoteLog.OrderByDescending(x => x.LogDate).Where(x => x.Id >= (id - 1)).Take(3);
}
  • 如果结果中有 3 个项目,您将拥有上一个、下一个和当前
  • 如果结果中有 2 项,则您的 id 是最后一页
  • 如果有 1 或 0 项,则您的 id 无效

可能需要更多思考(例如,如果您的 id < 2 怎么办),但这是一条潜在的路径

于 2012-11-28T16:39:38.720 回答
0

我认为这是一个很好的挑战,所以我打开笔记本电脑试了一下。

我沿着我的第一个答案的路线走,但实际上为了有 2 个查询而不是 3 个查询,它产生了很多糟糕的代码。所以我把它简化了。如果您在CreatedId列上都放置一个索引,这应该会很快工作。

PageService是您要查看的类。

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<MyDbContext>(null);

        var context = new MyDbContext(@"Data Source=.;Initial Catalog=Play;Integrated Security=True;");

        PageService service = new PageService(context);
        while (true)
        {
            Console.WriteLine("Please enter a page id: ");
            var pageId = Console.ReadLine();

            var detail = service.GetNavigationFor(Int32.Parse(pageId));

            if (detail.HasPreviousPage())
            {
                Console.WriteLine(@"Previous page ({0}) {1} {2}", detail.PreviousPage.Id, detail.PreviousPage.Name, detail.PreviousPage.Created);
            }
            else
            {
                Console.WriteLine(@"No previous page");
            }

            Console.WriteLine(@"Current page ({0}) {1} {2}", detail.CurrentPage.Id, detail.CurrentPage.Name, detail.CurrentPage.Created);


            if (detail.HasNextPage())
            {
                Console.WriteLine(@"Next page ({0}) {1} {2}", detail.NextPage.Id, detail.NextPage.Name, detail.NextPage.Created);
            }
            else
            {
                Console.WriteLine(@"No next page");
            }

            Console.WriteLine("");
        }


    }
}

public class PageService
{
    public MyDbContext _context;

    public PageService(MyDbContext context)
    {
        _context = context;
    }

    public NavigationDetails GetNavigationFor(int pageId)
    {
        var previousPage = _context.Pages.OrderByDescending(p => p.Created).Where(p => p.Id < pageId).FirstOrDefault();
        var nextPage = _context.Pages.OrderBy(p => p.Created).Where(p => p.Id > pageId).FirstOrDefault();
        var currentPage = _context.Pages.FirstOrDefault(p => p.Id == pageId);

        return new NavigationDetails()
        {
            PreviousPage = previousPage,
            NextPage = nextPage,
            CurrentPage = currentPage
        };
    }
}

public class NavigationDetails
{
    public Page PreviousPage { get; set; }
    public Page CurrentPage { get; set; }
    public Page NextPage { get; set; }

    public bool HasPreviousPage()
    {
        return (PreviousPage != null);
    }

    public bool HasNextPage()
    {
        return (NextPage != null);
    }
}

public class MyDbContext : DbContext
{
    public MyDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    public DbSet<Page> Pages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PageMap());
    }

}

public class PageMap : EntityTypeConfiguration<Page>
{

    public PageMap()
    {
        ToTable("t_Pages");

        Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(m => m.Name);
        Property(m => m.Created);
    }

}

public class Page
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
}

}

SQL 代码

USE [Play]
GO

/****** Object:  Table [dbo].[t_Pages]    Script Date: 11/28/2012 20:49:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[t_Pages](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Created] [datetime] NULL,
 CONSTRAINT [PK_t_Page] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
于 2012-11-28T20:51:34.927 回答