实体框架5.0问题。
我是Entity Frame的新手,基本上我有一个表“MyPIN”。
[Table("MyPIN")]
public class BatchPINDetail
{
public BatchPINDetail();
public int Number { get; set; }
我想运行查询
int x = the biggest Number FROM MyPIN
对应的代码是:
public class InContext : DbContext
{
public InContext();
public InContext(string connectionString);
public DbSet<BatchDetail> BatchDetailsRecords { get; set; }
}
问题1:我不确定如何检索它。
问题2:获得值后,我想重新分配值,比如Number + = 1;我需要把它写到DB。
感谢您的帮助。
答案 0 :(得分:0)
InContext inContext = new InContext(cnStr);
// get first biggest item
BatchPINDetail entity = inContext.BatchDetailsRecords
.OrderByDescending(x => x.Number)
.First();
// get all biggest items
BatchPINDetail entities = inContext.BatchDetailsRecords
.Where(x => x.Number == x.Max(x => x.Number))
.ToArray();
// and if you just want to get biggest number.
// but note that if you just change `num` nothing will happen.
int num = inContext.BatchDetailsRecords.Max(x => x.Number);
entity.Number += 1;
inContext.SaveChanges();
答案 1 :(得分:0)
您可以像以下代码一样使用直接方法,避免对数据库进行反向调用。
InContext inContext = new InContext(cnStr);
string Sql="SELECT * FROM MyPIN where Number in (Select MAX(Number) from MyPIN)";
BatchPINDetail[] entities = inContext.BatchDetailsRecords.SqlQuery(Sql).ToArray();
现在您可以进行更改并在此之后调用SaveChanges()。