EF Core-如何检索聚合根的关联实体? [英] EF Core - How can I retrieve associated entities of an aggregate root?

查看:184
本文介绍了EF Core-如何检索聚合根的关联实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我试图在为一个简单的基金帐户建模时遵循DDD.

In my app I am trying to follow DDD whilst modelling a simple fund account.

类是

FundAccount

public Guid Id { get; set; }

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

public IReadOnlyCollection<AccountTransaction> Transactions => _transactions
            .OrderByDescending(transaction => transaction.TransactionDateTime).ToList();

帐户交易

public Guid Id { get; set; }

public decimal Amount { get; set; )

我正在尝试从数据库中检索包含以下交易的资金帐户:

I am trying to retrieve the fund account from the database with the transactions included with the following:

var fundAccount = await _context.FundAccounts
                 .Include(a => a.Transactions)
                 .SingleAsync(a => a.Id == ...);

当我检索FundAccount(数据库中有交易记录)时, Transactions 有0个 AccountTransaction ?

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

Can anyone see what I need to do here?

推荐答案

首先,在实体 data 模型中使用域逻辑"时(您不应该这样做,但这是另一回事了),请确保将EF Core配置为使用支持字段通过将以下内容添加到db上下文 OnModelCreating 覆盖中来代替属性(默认设置):

First, when using *domain logic" in the entity data model (which you shouldn't, but that's another story), make sure to configure EF Core to use backing fields instead of properties (the default), by adding the following to the db context OnModelCreating override:

modelBuilder.UsePropertyAccessMode(PropertyAccessMode.Field);

此btw已被视为问题,将在3.0版本中修复-请参见重大更改-默认情况下使用后备字段.但是目前,您必须包含上面的代码.

This btw has been recognized as issue and will be fixed in the 3.0 version - see Breaking Changes - Backing fields are used by default. But currently you have to include the above code.

第二,您必须更改背景字段 type 以与属性类型兼容.

Second, you have to change the backing field type to be compatible with the property type.

在您的情况下, ICollection< AccountTransaction> IReadOnlyCollection< AccountTransaction> 不兼容,因为前者不继承后者的历史原因.但是 List< T> (以及其他集合 classes )实现两个接口,并且由于这是您用来初始化字段的方法,因此只需将其用作字段类型即可:

In your case, ICollection<AccountTransaction> is not compatible with IReadOnlyCollection<AccountTransaction>, because the former does not inherit the later for historical reasons. But the List<T> (and other collection classes) implement both interfaces, and since this is what you use to initialize the field, simply use it as a field type:

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

完成这两个修改后,集合导航属性将由EF Core正确加载.

With these two modifications in place, the collection navigation property will be correctly loaded by EF Core.

这篇关于EF Core-如何检索聚合根的关联实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆