EF Core - How can I retrieve associated entities of an aggregate root?

吃可爱长大的小学妹 提交于 2020-01-05 04:27:12

问题


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

The classes are

FundAccount

public Guid Id { get; set; }

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

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

AccountTransaction

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 == ...);

When I retrieve the FundAccount (which has transactions in the database) Transactions has 0 AccountTransaction?

Can anyone see what I need to do here?


回答1:


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);

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.

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

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>();

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



来源:https://stackoverflow.com/questions/57429933/ef-core-how-can-i-retrieve-associated-entities-of-an-aggregate-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!