【问题标题】:Using DBContext to Select Fields使用 DBContext 选择字段
【发布时间】:2013-09-08 18:26:13
【问题描述】:

我有几个关于 DBContext 和实现我想要的结果的问题。 我可以像这样检索数据

---Model
   public class InvoiceModel
{
    [Key]
    public int? Invoice_Number { get; set; }
    public decimal Amt_Total { get; set; }
    public decimal Amt_Due { get; set; }
    public decimal Amt_Paid { get; set; }

    public List<InvoiceModel> GetInvoice()
    {
        using (VuittonEntities db = new VuittonEntities())
        {
            return (from inv in db.Invoice
                    select new InvoiceModel
                    {
                        Invoice_Number = inv.Invoice_,
                        Amt_Total = inv.AmountTotal,
                        Amt_Due = inv.AmountDue,
                        Amt_Paid = inv.AmountPaid
                    }).ToList();
        }
    }

--- Controller
public ViewResult Index()
    {
      var data = new InvoiceModel().GetInvoice();
      return View(data);
    }

这几乎是标准的 LinQ,它返回包含我选择的 4 个字段的发票表。但现在我想使用 DB Context 来实现这一点。所以我将这个新类添加到我的控制器中,并在视图中这样调用它。

 Controller 
public class VuittonEntities : DbContext
    {
        public DbSet<InvoiceModel> Invoice { get; set; }
    }
 View
   public ViewResult Index()
    {
          VuittonEntities db = new VuittonEntities();       
          return View(db.Invoice.ToList());
    }

它返回整个表,我必须注释掉我的 List'InvoiceModel' 类

假设: VuittonEntities 是我的连接字符串名称, 发票是表 Vuitton 是我的 .edmx 课程—— 我听说这可以在不使用 Select 语句的情况下实现。看来我没有将我的模型类链接到 LinQ 实体,但是当我添加我的上下文类时,它会在我的 List{InvoiceModel} 类中的 inv."FieldName" 列上引发错误。

TLDR 版本: 如何从 DbContext 类而不是整个表中返回选定的字段 为什么添加 DBContext 类会在我的 List(ModelClass) 字段上引发错误

【问题讨论】:

    标签: asp.net-mvc entity-framework dbcontext


    【解决方案1】:

    如果您不想要整张桌子,那么不要只在DbSet 上拨打ToList(),因为这只会抓住您所看到的所有桌子。您在使用@ 时做对了987654323@,因为 Select 语句旨在创建从一组数据到新形式(新类、模型、匿名对象)的投影。

    【讨论】:

    • 好的,有人告诉我不需要选择语句,但是还有另一种方法,对此有什么想法吗?另外,当我添加 DbContext 类时,您能否说明我的 List 类错误的原因?
    • 我能想到的唯一方法是在没有 Select 的情况下使用 SQL 视图,并将视图映射到 DbContext 中......我可能会结束坚持选择虽然..此外,如果您需要有关错误的帮助,您必须说出错误是什么!最后,我会认真考虑将您的一些逻辑分开,例如 InvoiceModel 类中的 GetInvoice 方法——它应该在其他地方,例如在服务层或存储库中。最后,对于存储在数据库中的实体,您的 Key 不应为空。
    • 你的权利我不应该有那个可为空的列,我有一个 ID 字段,我将使用它。我的 inv."field" 指向我的实体表,但是当我输入 DB Context 字段时,它指向我的模型类。我正计划将它移到数据层中,我想在添加另一个步骤之前让它工作,我现在要尝试一下,看看会发生什么。
    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多