【问题标题】:Retrieve a number from a table by EF通过 EF 从表中检索一个数字
【发布时间】:2012-11-12 16:20:05
【问题描述】:

Entity Frame 5.0 问题。

我是实体框架的新手,基本上我有一个表“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;我需要将其写入数据库。

感谢您的帮助。

【问题讨论】:

    标签: c# sql-server-2008 entity-framework c#-4.0


    【解决方案1】:
    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();
    

    【讨论】:

    • 可能有重复,说大的数是50,有好几个50,可以吗?
    • 我想得到这个数字,比如说 int x = inContext.BatchDetailsRecords .OrderByDescending(x => x.Number) .First();
    【解决方案2】:

    您可以使用类似以下代码的直接方法,避免来回调用数据库。

        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()。

    【讨论】:

      猜你喜欢
      • 2011-12-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2019-08-15
      • 1970-01-01
      相关资源
      最近更新 更多