gpt4 book ai didi

C# 保存历史表与具有依赖注入(inject)的 Entity Framework 的接口(interface)

转载 作者:行者123 更新时间:2023-12-05 07:07:13 25 4
gpt4 key购买 nike

我们将 Net Core 2 与 Entity Framework 结合使用。我们的Sql数据库由很多表组成,Address, Account, Customer, Sales等。

有些表有对应的历史表:AddressHistory、CustomerHistory、

任何时候有人更改原始表中的某些内容,都应更新相应的历史表。 (不能使用 sql 时态表,因为我们有自定义历史逻辑)

我们正在尝试应用接口(interface),我不太了解代码,有人可以提供一个快速的代码示例来说明如何使用接口(interface)实现它吗?尤其是SaveHistory部分,如何应用依赖注入(inject)?随意根据需要重写代码

public partial class TestDbContext
{

public void AddEntityHistory<IEntityHistory>(IEntityHistory entity) where IEntityHistory: Address
{
// do something 1 etc
}

public void AddEntityHistory<IEntityHistory>(IEntityHistory entity) where IEntityHistory: Customer
{
// do something 2 etc
}

public override int SaveChanges()
{
SaveEntityHistory();
return base.SaveChanges();
}

protected void SaveEntityHistory()
{
var modifiedEntities = ChangeTracker.Entries<IEntityHistory>().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach(var entity in modifiedEntities)
{
AddEntityHistory(entity); // what is the code base here? giving error below, it should call appropriate AddEntityHistory Method for corresponding Entity
}
}
}

上面的错误:

Error CS0311 The type 'Interfaces.IEntityHistory' cannot be used as type parameter 'IEntityHistory' in the generic type or method 'PropertyContext.AddEntityHistory(IEntityHistory)'. There is no implicit reference conversion from 'Interfaces.IEntityHistory' to 'Data.Entities.Address'.

资源:

尝试利用类似的代码库:用于 CreateDate、UserId 等

https://dotnetcore.gaprogman.com/2017/01/26/entity-framework-core-shadow-properties/

最佳答案

方法的通用形式在这里根本不起作用。反射更适合你的要求:

public partial class TestDbContext
{

public void AddEntityHistory(Address entity)
{
// do something 1 etc
}

public void AddEntityHistory(Customer entity)
{
// do something 2 etc
}

public override int SaveChanges()
{
SaveEntityHistory();
return base.SaveChanges();
}

protected void SaveEntityHistory()
{
var modifiedEntities = ChangeTracker.Entries<IEntityHistory>()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (var entity in modifiedEntities)
{
var methodInfo = this.GetType().GetMethod(nameof(AddEntityHistory), new[] { entity.Entity.GetType() });
methodInfo.Invoke(this, new[] { entity.Entity });
}
}
}

关于C# 保存历史表与具有依赖注入(inject)的 Entity Framework 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62268390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com