简体   繁体   English

扩展实体框架保存在单个实体类型上

[英]Extend Entity Framework Save on a single Entity Type

I have a rather large save routine that updates hundreds of items using the Entity Framework and then saves the whole lot in one go. 我有一个相当大的保存例程,使用实体框架更新数百个项目,然后一次性保存整个批次。

using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2; // Audit item
    dc.Entity2.Prop3 = 3; // Audit item
    dc.Entity3.Prop1 = 1;
    ...
    dc.SaveChanges();
}

What I would love to be able to do is somehow either extend the Save for an individual Entity or pick up on this change and kick off another method. 我希望能够以某种方式扩展单个实体的保存或接受此更改并启动另一种方法。

The main purpose of this is to hook into our Audit system, which only audits some key items, (so for example only Entity2.Prop2 and Entity2.Prop3 in the simplified version above) but would also possibly kick off some other routines, creating tasks etc, but the crux is - can it be done? 这样做的主要目的是挂钩我们的审计系统,它只审计一些关键项目(例如,上面的简化版本只有Entity2.Prop2和Entity2.Prop3),但也可能启动其他一些例程,创建任务等等,但关键是 - 可以做到吗?

Basically I'm aiming to remove the extra audit line we have to put in for specific types as below: 基本上我的目标是删除我们必须为特定类型添加的额外审计行,如下所示:

using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop2", From = oldVal, To = 2}
    dc.Entity2.Prop3 = 3;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop3", From = oldVal, To = 3}
    ...
    dc.SaveChanges();
}

The only way is override SaveChanges , find changed entities and call your routines for them. 唯一的方法是覆盖SaveChanges ,找到更改的实体并为它们调用您的例程。

public override int SaveChanges()
{
    var entities = ChangeTracker.Entries<Entity1>()
                                .Where(e => e.State == EntityState.Modified)
                                .Select(e => e.Entity);

    foreach(var entity in entities)
    {
        // call your rutine.
    }

    return base.SaveChanges();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM