首页 > 解决方案 > 如何在 C# 的 Entity Framework Core 中加入 2 个表以使用 linq/lambda 表达式创建对象的新实例?

问题描述

我在 ASP.NET Core Web API 中使用 Entity Framework Core 和 PostGreSQL。

我很难找出合适的 lambda/linq 表达式来填充查询中的字段。

我可以用 foreach() 循环来做这件事,但我确信有一种更有效的方法来完成任务。

考虑以下表定义:

public class A
{
    [Key]
    public Guid AId { get; set; }
    public string AName { get; set; }
    public Guid BId { get; set; }
    [NotMapped] 
    public B BType { get; set; }
}

public class Consumer
{
    [Key]
    public Guid BId { get; set; }
    public string BName { get; set; }
    public string OtherInfo { get; set; }
}

public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }

public A GetAById(Guid p_Id)
{
    A result = null;

    using (Scope scope = AsyncScopedLifestyle.BeginScope(_container))
    {
        var dbContext = _container.GetInstance<FooDBContext>();
        result = dbContext.As.Where(x => x.AId == p_Id).FirstOrDefault();
        // How would I populate A->B with corresponding value from Bs Table?
    }

    return result;
}

result = dbContext.As.Where(x => x.AId == p_Id).FirstOrDefault();

我将如何填充A -> BBs 表中的相应值?

我假设我会做某种选择并将结果投影到A的新实例中?

标签: c#linqentity-framework-core

解决方案


推荐阅读