C# EF Core-如何检索聚合根的关联实体?

C# EF Core-如何检索聚合根的关联实体?,c#,entity-framework,ef-code-first,ef-core-2.1,C#,Entity Framework,Ef Code First,Ef Core 2.1,在我的应用程序中,我尝试跟踪DDD,同时模拟一个简单的基金账户 课程是 基金账户 public Guid Id { get; set; } private ICollection<AccountTransaction> _transactions = new List<AccountTransaction>(); public IReadOnlyCollection<AccountTransaction> Transactions => _trans

在我的应用程序中,我尝试跟踪DDD,同时模拟一个简单的基金账户

课程是

基金账户

public Guid Id { get; set; }

private ICollection<AccountTransaction> _transactions = new List<AccountTransaction>();

public IReadOnlyCollection<AccountTransaction> Transactions => _transactions
            .OrderByDescending(transaction => transaction.TransactionDateTime).ToList();
我正在尝试从数据库中检索包含以下交易的基金帐户:

var fundAccount = await _context.FundAccounts
                 .Include(a => a.Transactions)
                 .SingleAsync(a => a.Id == ...);
当我检索FundAccount(数据库中有交易记录)时,
transactions
有0
AccountTransaction


有人能看到我需要在这里做什么吗?

首先,在实体数据模型中使用*domain logic”(您不应该这样做,但这是另一种情况)时,请确保配置EF Core以使用而不是属性(默认设置),方法是将以下内容添加到db上下文
OnModelCreating
覆盖:

modelBuilder.UsePropertyAccessMode(PropertyAccessMode.Field);
顺便说一句,此问题已被确认为问题,并将在3.0版本中修复-请参阅。但目前您必须包含上述代码

其次,必须更改支持字段类型以与属性类型兼容

在您的情况下,
ICollection
IReadOnlyCollection
不兼容,因为前者由于历史原因不会继承后者。但是
List
(和其他集合类)实现了这两个接口,因为这是您用来初始化字段的,只需将其用作字段类型:

private List<AccountTransaction> _transactions = new List<AccountTransaction>();
private List_transactions=new List();

有了这两个修改,EF Core将正确加载集合导航属性。

AccrountTransaction与FoundAccount之间的关系是什么?没有属性FoundAccountId…是否正确?
private List<AccountTransaction> _transactions = new List<AccountTransaction>();