问题
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 0AccountTransaction
?
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