使用 Entity Framework 4.1 创建历史表
我正在开发 asp.net MVC 3 应用程序,并且使用 codeFirst 方法。我正在尝试创建历史表或用户表,我想在其中跟踪用户修改了哪些列。我如何使用 EF Code First 来做到这一点。
我需要在 DataContext.savechanges 之后执行此操作吗?
请建议。
谢谢。
I am working on asp.net MVC 3 application and I am using codeFirst approach. I am trying to create history table or user table, Where I want to keep track of what columns were modified by user. How can I do this using EF Code First.
Do I need to do it after DataContext.savechanges ?
Please suggest.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,您想要一个继承自 ActionFilterAttribute 的过滤器。就我而言,这是我拥有的最简单的例子。这是我的模型,请注意属性决定了到数据库的映射。
就我而言,它就像下面这样简单,尽管它不是历史性的:
最终结果不仅是 EF 是代码优先,而且还允许您的视图模型使用从复杂实体派生的基元。现在,如果您有另一个(比如说历史数据库)DBContext,那么我建议您修改文本转换文件或为您的实体创建一个基类。这两种方法都可以轻松生成可以插入表中的代码,然后跟踪该实体,将其克隆到历史模型中并保存。话虽这么说,我是数据库优先方法的粉丝,专注于约束、触发器等,而不是框架。
Sounds to me like you want an a filter that inherits from ActionFilterAttribute. In my case, this is the simplest example that I have. This is my model, notice that the attributes dictate the mapping to the database.
In my case, it was as simple as the following, although it was not historical:
The end result is not only EF being code first, but also allows for your models for your views to use primitives derived from your complex entities. Now, if you have another, lets say historical, DBContext then I would recommend modifying either the text transformation file or creating a base class for your entities. Both ways allow for an easy generation of code that could insert into your table, then follow up with that entity, clone it into a historical model and save. All that being said, I am a fan of database first approaches with concentration on constraints, triggers, etc. instead of a framework.
DbContext 有一个名为
Entry
的方法:条目的类型为
DbEntityEntry
并具有属性OriginalValues
和当前值
。您可能可以编写一些内容来一般性地检查这些属性以查看发生了什么变化,然后自动将新记录插入到历史表中。
要么使用数据库触发器。
The DbContext has a method called
Entry<T>
:entry will be of type
DbEntityEntry<T>
and has the propertiesOriginalValues
andCurrentValues
.You could probably write something that will generically inspect these properties to see what has changed and then automatically insert a new record into your history table.
Either that, or use database triggers.
我不确定这是否真的是“适当”的方法,但这就是它通常在 sql 中完成的方式:
version
。IsLatestVersion
IsLatestVersion
= false。版本
,并将更改保存为新实体。I'm not sure if this is really the "appropiate" way to do it, but this is how its usually done in sql:
version
of type int or something.IsLatestVersion
of type boolIsLatestVersion
= false.version
, and save the changes as new entity.