【问题标题】:How to insert to collection of a parent class using EF Core如何使用 EF Core 插入到父类的集合
【发布时间】:2020-06-20 20:19:49
【问题描述】:

我首先设置了 EF 代码,其中 帐户可以有许多交易

public class Account : BaseEntity
{
    public string AccountNumber { get; set; }
    public string AccountTitle { get; set; }
    public decimal CurrentBalance { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public AccountStatus AccountStatus { get; set; }
    public  ICollection<Transaction> Transactions { get; set; }
}
public enum AccountStatus
{
    Active = 0,
    InActive = 1
}

事务是这样设置的。

 public class Transaction : BaseEntity
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public TransactionType TransactionType { get; set; }
    public DateTime TransactionDate { get; set; }
    public decimal TransactionAmount { get; set; }
    public Account Account { get; set; }
}
public enum TransactionType
{
    Deposit = 0,
    Withdraw = 1
}

Add 方法的通用 repo 实现是这样的

public  TEntity Add(TEntity t)
    {           
            t.Id = Guid.NewGuid().ToString();
            DbSet.Add(t);
            return t;                                
    }

我也有一个使用工作单元实现的通用存储库。

在服务层我正在添加这样的事务

 public async Task<Transaction> AddTransaction(Transaction transaction, string accountId)
    {
       // var account = await _unitOfWork.AccountRepository.GetAsync(accountId);
        // transaction.Account = account;
        var result =  _unitOfWork.TransactionRepositoy.Add(transaction);
        await _unitOfWork.CommitAsync();
        return result;
    }

CommitAsync 只是调用 _context.SaveChangesAsync();

当我添加交易时,如何判断我为哪个账户添加交易? 因为如上所述。 Account 可以有很多 Transactions (ICollection) 并且 Transaction 属于一个 Account (Navigation Property Account)。

【问题讨论】:

  • 我缺少“附加”吗?如果是,那么如何实施?

标签: entity-framework asp.net-core entity-framework-core


【解决方案1】:

由您决定将交易添加到哪个帐户。这 这里的accountId参数应该是你需要添加的Account。

我认为你注释掉的两行正是你所需要的

首先,the accountId you pass represents the data of the Account that the transaction needs to be associated with,并确保 Account 表包含这个 accountId 数据。

根据accountId从数据库中获取Account数据,然后赋值给Transaction的Account字段保存。

常见的efcore实现代码:

   public async Task<Transaction> AddTransaction(Transaction transaction, string accountId)
    {
        transaction.Account = _context.Account.Find(accountId)
         _context.Transaction.Add(transaction);
        await _context.SaveChangesAsync(); 
        return transaction;
    }

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2021-03-29
    • 2021-10-21
    相关资源
    最近更新 更多