我非常确定我使用此代码段在右侧,但我尝试做的是在带有导航控件的页面上显示特定记录,这样您就可以转到next和previous记录(MVC3中生成的Details视图页面的修改版本)。
当我导航到页面时,代码通过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。
感谢你们的建议:)。
答案 0 :(得分: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);
}
可能需要更多的思考(例如,如果你的身份&lt; 2),但它的潜在路径
答案 1 :(得分:0)
我认为这是一个相当不错的挑战,所以我打破了笔记本电脑,然后试了一下。
我沿着我的第一个回答的路线走了,但实际上是为了有2个查询而不是3个,它产生了很多糟糕的代码。所以我简化了它。如果您在已创建和 ID 列上添加了索引,则此操作应该很快。
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