【问题标题】:Invoking child nodes Entity Framework Core调用子节点实体框架核心
【发布时间】:2019-02-19 18:20:58
【问题描述】:

我是这种对象编程的新手,你介意帮助我吗?

我必须调用子节点,但要调用特定字段,但我不知道该怎么做。我已经研究了很多地方,但它似乎不起作用。

例如,我只想要RepunicAccount 中的FirstName,以及来自RepunicAccountType 的所有其他信息,或类似的信息。

我的DbContext

public class RepunicContext : DbContext 
{
    public virtual DbSet<RepunicAccount> RepunicAccount { get; set; }
    public virtual DbSet<RepunicAccountType> RepunicAccountType { get; set; }

    protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) 
    {
        optionsBuilder.UseSqlServer ("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Repunic;Data Source=DESKTOP-        6I8LD45\\SQLEXPRESS_ERICH");
    }

    public RepunicContext (DbContextOptions<RepunicContext> options) :base (options)
    { }

    public RepunicContext () { }
}

我的模型课:

public class RepunicAccount 
{
    public int ID { get; set; }
    public string Email { get; set; }

    public string Username { get; set; }
    public string Password { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    [ForeignKey ("ID_Type")]
    public int? ID_Type { get; set; }

    public ICollection<RepunicAccountType> TipoConta { get; set; }

    public DateTime? DataCadastro { get; set; } = DateTime.Now;
    public DateTime? DataAlteracao { get; set; } = DateTime.Now;
}

我的子节点类:

public class RepunicAccountType 
{
    [Key]
    public int ID_Type { get; set; }

    public string Descricao { get; set; }
    public DateTime DataCadastro { get; set; } = DateTime.Now;
    public DateTime DataAlteracao { get; set; } = DateTime.Now;
}

我有一个存储库,这是我进行编码的地方,在放入控制器之前,它在每个地方都几乎相同,但我将展示我试图在两个地方使用的示例.

public IEnumerable<RepunicAccount> GetAllByIDType () 
{
    var data = db.RepunicAccount.Where (a => a.ID_Type != null)
                                .Include (p => p.types);
    var type = db.RepunicAccountType.OrderBy (b => b.Descricao);

    return data.ToList();
}

问题是:我没有t know how to invoke specific items nor make anything else other thanToList();`

那么,我该怎么办?如果我可以发送更多信息,请询问我。

【问题讨论】:

  • 您有与此代码关联的控制器和视图吗?您的目标是 Web 还是桌面?
  • 你试过.Select吗?

标签: c# asp.net-core-mvc entity-framework-core


【解决方案1】:

我很想发表评论,但是我没有这样做所需的声誉。

由于您是该主题的新手,请务必遵循文档。

EF Core Documentation

我还创建了一个 youtube 视频以供入门,我建议您花几分钟时间观看。

Video on EF Core

简而言之,您需要一个 DBContext 和您的模型。然后,您可以开始查询数据并以您希望的格式返回。像这样:

    using (var context = new RepunicContext())
      {
        var accounts = context.RepunicAccounts.ToList();
      }

accounts 然后会有一个您可以遍历的每个帐户的列表。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2020-05-10
    • 2020-09-12
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多