【问题标题】:How to implement IEnumerable in my specific case?如何在我的特定情况下实现 IEnumerable?
【发布时间】:2016-07-20 07:31:37
【问题描述】:

以前有人问过我的问题,但即使之前的所有帖子我也无法弄清楚。显然我没有正确理解。

我让 Visual Studio 生成一个 ADO NET 实体框架模型,首先从数据库中生成代码。在数据库中,我有一个名为 Finishes 的表(用于保存游戏的所有可能结局,只是为了澄清)。这一切都很好。现在我需要实现 IEnumerable 以便能够遍历它。到目前为止,我什么都明白了。我似乎无法以某种方式做到这一点。也许有人可以将他们的光芒照耀在上面,这样我就会一劳永逸地理解。

Visual Studio 已经生成了两个类;

Checkoutlist.cs:

namespace Bull.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Collections;

public partial class CheckoutList : DbContext, IEnumerable
{
    public CheckoutList()
        : base("name=DatastoreConnection")
    {
    }

    public virtual DbSet<Finish> Finishes { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Finish>()
            .Property(e => e.First)
            .IsFixedLength();

        modelBuilder.Entity<Finish>()
            .Property(e => e.Second)
            .IsFixedLength();

        modelBuilder.Entity<Finish>()
            .Property(e => e.Third)
            .IsFixedLength();
    }
}
}

还有 Finish.cs:

namespace Bull.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

public partial class Finish
{
    public int Id { get; set; }

    public int Total { get; set; }

    [Required]
    [StringLength(10)]
    public string First { get; set; }

    [Required]
    [StringLength(10)]
    public string Second { get; set; }

    [Required]
    [StringLength(10)]
    public string Third { get; set; }
}
}

所以问题是;在我的情况下如何实现 IEnumerable?非常感谢您的帮助(以及可能的解释)。

【问题讨论】:

  • "数据库中的代码优先" 代码优先是从代码生成数据库而不是从数据库中生成代码的方法
  • 我不明白,Finishes 已经实现了IEnumerable&lt;Finish&gt;。你的CheckoutList 是DbContext,它不应该实现IEnumerable。
  • 感谢 MegaTron。所以你的意思是我一开始就使用了错误的方法,这是我的问题?
  • @MegaTron Code-first 用词不当。后来 EF 团队将其重命名为“基于代码的建模”,因为它支持两个方向(请参阅here)。
  • 你还没有显示你的Checkouts-class。您的CheckoutList 是DbContext,因此它是您无法枚举的数据库实例,如果您想枚举所有Finish,则必须使用Finishes 属性:using(var db = new CheckoutList()) foreach(Finish f in db.Finishes)Console.WriteLine("{0}:{1}:{2}",f.First,f.Second,f.Third);

标签: c# entity-framework ienumerable


【解决方案1】:

尝试使用这种方法:

public IEnumerable<Finish> Get()
{
     var query = base.Set<Finish>();
     return query.ToList();
}

【讨论】:

  • 谢谢@MegaTron,这正是我想要的!
  • 很高兴能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
相关资源
最近更新 更多