如何在多对多关系中保存 EF Core 3.1.3 中的更改?
How to save changes in EF Core 3.1.3 in a many to many relationship?
我正在尝试使用 EF Core 3.1.3、.net core 3.1 和 blazor 页面保存对数据库的更改。该模型包含多个children,每个child有另一个child可能是同一个实体。这是示例代码:
public class Currency
{
[Key]
public int CurrencyID { get; set; }
public string Country{ get; set; }
public string Name{ get; set; }
public string ISOCode{ get; set; }
public bool Active{ get; set; }
}
public class PaymentDetail
{
[Key]
public int PaymentDetailID{ get; set; }
public DateTime Date{ get; set; }
public decimal Amount{ get; set; }
[ForeignKey("CurrencyID")]
public int CurrencyID{ get; set; }
public Moneda Currency{ get; set; }
}
public class Payment
{
[Key]
public int PaymentID{ get; set; }
public string ReferenceNumber{ get; set; }
public ICollection<PaymentDetail> PaymentDetail{ get; set; }
[ForeignKey("CurrencyID")]
public int CurrencyID{ get; set; }
public Currency Currency{ get; set; }
public decimal TotalAmount{ get; set; }
}
如您所见,我有多个 children 将使用相同的货币,parent 也可能使用相同的货币,因此当我尝试保存更改时,我得到了一个已跟踪具有相同 currencyID 的实体的错误。
我知道一种解决方案是在尝试保存更改之前使所有导航属性无效,这适用于将数据保存到数据库中,但由于我正在向用户显示一些属性,所以会破坏我的 blazor 页面。
我尝试使用 State.Unchanged 而不是使导航无效 属性 但是当我遍历所有 children 并且有第二个 child 使用相同的货币然后我有实体已经被跟踪的错误。
我还在查询中使用了 .AsNoTracking() 来获取货币,但它也被跟踪了,我想当我使用 dbcontext.Add(Payment) 时会发生这种情况。
还有其他解决办法吗?也许是一种检查实体是否已处于未更改状态的方法,以便我可以在迭代期间跳过它?
感谢您的帮助
我最终创建了一个新的 Payment 实例,并且只复制了我想保存到新实例中的信息。这样我就把视图和模型分开了。
我正在尝试使用 EF Core 3.1.3、.net core 3.1 和 blazor 页面保存对数据库的更改。该模型包含多个children,每个child有另一个child可能是同一个实体。这是示例代码:
public class Currency
{
[Key]
public int CurrencyID { get; set; }
public string Country{ get; set; }
public string Name{ get; set; }
public string ISOCode{ get; set; }
public bool Active{ get; set; }
}
public class PaymentDetail
{
[Key]
public int PaymentDetailID{ get; set; }
public DateTime Date{ get; set; }
public decimal Amount{ get; set; }
[ForeignKey("CurrencyID")]
public int CurrencyID{ get; set; }
public Moneda Currency{ get; set; }
}
public class Payment
{
[Key]
public int PaymentID{ get; set; }
public string ReferenceNumber{ get; set; }
public ICollection<PaymentDetail> PaymentDetail{ get; set; }
[ForeignKey("CurrencyID")]
public int CurrencyID{ get; set; }
public Currency Currency{ get; set; }
public decimal TotalAmount{ get; set; }
}
如您所见,我有多个 children 将使用相同的货币,parent 也可能使用相同的货币,因此当我尝试保存更改时,我得到了一个已跟踪具有相同 currencyID 的实体的错误。
我知道一种解决方案是在尝试保存更改之前使所有导航属性无效,这适用于将数据保存到数据库中,但由于我正在向用户显示一些属性,所以会破坏我的 blazor 页面。
我尝试使用 State.Unchanged 而不是使导航无效 属性 但是当我遍历所有 children 并且有第二个 child 使用相同的货币然后我有实体已经被跟踪的错误。
我还在查询中使用了 .AsNoTracking() 来获取货币,但它也被跟踪了,我想当我使用 dbcontext.Add(Payment) 时会发生这种情况。
还有其他解决办法吗?也许是一种检查实体是否已处于未更改状态的方法,以便我可以在迭代期间跳过它?
感谢您的帮助
我最终创建了一个新的 Payment 实例,并且只复制了我想保存到新实例中的信息。这样我就把视图和模型分开了。