C#EF如何将一个实体类多个对象的状态保存在一张状态表中并按照时间存储
时间: 2023-12-03 10:46:33 浏览: 51
可以通过以下步骤实现将一个实体类多个对象的状态保存在一张状态表中并按照时间存储:
1. 创建一个状态表的实体类,包含以下字段:
- Id: 状态表主键
- EntityId: 实体类对应的主键
- EntityType: 实体类的类型
- PropertyName: 实体类中需要保存状态的属性名
- OldValue: 实体类中需要保存状态的属性旧值
- NewValue: 实体类中需要保存状态的属性新值
- CreatedTime: 状态记录的创建时间
2. 在实体类中定义一个方法,该方法用于将实体类中需要保存状态的属性的旧值和新值存储到状态表中。例如:
```csharp
public void SaveState()
{
using (var context = new MyDbContext())
{
foreach (var prop in this.GetType().GetProperties())
{
if (prop.GetCustomAttributes(typeof(SaveStateAttribute), true).Length > 0)
{
var state = new EntityState
{
EntityId = this.Id,
EntityType = this.GetType().FullName,
PropertyName = prop.Name,
OldValue = prop.GetValue(this, null)?.ToString(),
NewValue = null,
CreatedTime = DateTime.Now
};
context.EntityStates.Add(state);
}
}
context.SaveChanges();
}
}
```
3. 在实体类中定义一个属性,该属性用于获取实体类中需要保存状态的属性的新值。例如:
```csharp
[SaveState]
public string Name { get; set; }
public string NewName { get; set; }
```
4. 在实体类中的属性 setter 方法中,将新值赋值给该属性,并将新值存储到状态表中。例如:
```csharp
public string Name
{
get { return _name; }
set
{
_name = value;
NewName = value;
SaveState();
}
}
```
5. 在查询状态记录时,可以按照创建时间倒序查询。例如:
```csharp
var states = context.EntityStates
.Where(e => e.EntityId == entityId && e.EntityType == entityType && e.PropertyName == propertyName)
.OrderByDescending(e => e.CreatedTime)
.ToList();
```
以上就是将一个实体类多个对象的状态保存在一张状态表中并按照时间存储的方法。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)