- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我们在一个项目上工作了 1 个月,有 6 个实体,与其他实体没有任何关系。它们都是简单的实体。
我们为每个实体的操作创建了 6 个不同的类。 SaveOrUpdateEntity()
类的方法和你想的差不多。是这样的:
public static ErrorType SaveOrUpdateEntity(Entity entity, int userID)
{
try
{
using (DataEntities ctx = new DataEntities())
{
if (entity != null)
{
if (entity.entityID == 0)
{
entity.CreateDate = DateTime.Now;
entity.CreatedBy = userID;
ctx.Entry(entity).State = EntityState.Added;
}
else
{
entity.ModifyDate = DateTime.Now;
entity.ModifiedBy = userID;
ctx.Entry(entity).State = EntityState.Modified;
}
}
ctx.SaveChanges();
}
return ErrorType.NoError;
}
catch (Exception ex)
{
return ErrorType.SaveError;
}
}
如果 SaveOrUpdateEntity()
方法通过覆盖 SaveChanges()
方法更短更通用,那将非常有帮助。根据其他关于覆盖 SaveChanges()
方法的问题、文章和帖子,实现存储实体状态的接口(interface)是一个很好的解决方案,但我也想知道其他解决方案。
因为我是新手,所有的答案将不胜感激。
谢谢。
最佳答案
您可以执行以下操作
1- 在您的应用程序中创建一个接口(interface),所有具有以下属性的类都将实现此接口(interface):Id、CreatedDate、CreatedBy、ModifiedDate、ModifiedBy
public interface ITrack
{
int Id{get; set;}
int CreatedBy{get; set;}
DateTime CreatedDate{get; set;}
int? ModifiedBy{get; set;} // int? because at first add, there is no modification
DateTime? ModifiedBy {get; set;}
}
Best practices Define the
CreatedBy
andModifiedBy
asstring
which will be good for performance and maintenance
2- 添加一个类 TrackableEntry
实现接口(interface) ITrack
public abstract class TrackableEntry : ITrack
{
public int Id{get; set;}
public int CreatedBy{get; set;}
public DateTime CreatedDate{get; set;}
public int? ModifiedBy{get; set;}
public DateTime? ModifiedBy {get; set;}
}
3- 从所有类中删除接口(interface)中提到的属性,让这些类直接从 TrackableEntry
实现
public class A: TrackableEntry
{
//public int Id{get; set;}
//public int CreatedBy{get; set;}
//public DateTime CreatedDate{get; set;}
//public int? ModifiedBy{get; set;}
//public DateTime? ModifiedBy {get; set;}
}
4- 在您的 DbContext
文件中覆盖您的 SaveChanges
并添加属性 UserId
或 UserName
如果您遵循*最佳实践*
部分
public int UserId{get; set;}
public override int SaveChanges()
{
this.ChangeTracker.DetectChanges();
var added = this.ChangeTracker.Entries()
.Where(t => t.State == EntityState.Added)
.Select(t => t.Entity)
.ToArray();
foreach (var entity in added)
{
if (entity is ITrack)
{
var track = entity as ITrack;
track.CreatedDate = DateTime.Now;
track.CreatedBy = UserId;
}
}
var modified = this.ChangeTracker.Entries()
.Where(t => t.State == EntityState.Modified)
.Select(t => t.Entity)
.ToArray();
foreach (var entity in modified)
{
if (entity is ITrack)
{
var track = entity as ITrack;
track.ModifiedDate = DateTime.Now;
track.ModifiedBy = UserId;
}
}
return base.SaveChanges();
}
最后,当您要调用 SaveChanges
方法时,请确保您设置了 UserId
或 UserName
值
var entities=new Entities(); // assuming that your DbContext file called Entities
// code for adding or deletion or modification here
entities.As.Add(new A(){...});
// ....
entities.UserId=MyUser;
entities.SaveChanges();
希望对你有帮助
关于c# - 覆盖 SaveChanges() 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26908301/
我一直想知道的一个问题是,我应该显式调用 context.SaveChanges() 还是让它在 Dispose() 下。 方法 1:自动保存 public virtual void Disp
我正在使用EF5和“数据库优先”方法在WPF中编写第一个MVVM应用程序。 我在MVVM中的模型是EF5为我生成的(我确实需要自定义T4模板以包括INotifyPropertyChanged)。 一切
我使用 Visual Studio 在 ASP.NET MVC 项目中处理本地数据库。 我在修改数据库时遇到问题。当我调用 SaveChanges() 时,我总是会收到此错误: The value c
我正在使用 Entity Framework 同时插入对象,如下所示。 context = new MyContext(); foreach (var x in lstX) { var abc
我在 ObjectSet 中添加数据并在 ObjectContext 上执行了 SaveChanges。但是新数据没有显示在 DataGrid 中! 代码: bsWork.DataSource = P
我正在使用 Oracle 数据库和 ASP.net MVC4 创建一个应用程序。即使在代码中看起来没有问题,调用 SaveChanges()方法导致此处显示的错误: 这张图片显示了内部异常和相关细节
我刚开始使用 Entity Framework ,我能够使用 linq 进行选择操作,但我在插入时遇到了问题。我试过这个示例,看看有什么问题: testEntities te = ne
假设我在 Controller 中调用了这样的东西: using (var context = new SqlContext()) { context.Items.Add(new Item("
我的 Asp.net mvc web 应用程序中有以下 Action 方法:- [HttpPost] [ValidateAntiForgeryToken] public ActionResult Cr
目标框架:netstandard2.0 Entity Framework 核心:2.2.6 我在 OnModelCreating 中有以下代码: protected override void OnM
这个问题在这里已经有了答案: DbContext SaveChanges Order of Statement Execution (1 个回答) 7年前关闭。 当上下文包含相关实体和 SaveCha
我有一个使用 Entity Framework 6.1、代码优先创建的 SQL-Azure 数据库。 我的“EmazeEvents”表中的“日期时间”字段是这样创建的: datetime = c.Da
查看人们编写的示例,我发现很多人使用 SaveChanges 而不是使用 SaveChangesWithRetries。我认为 SaveChangesWithRetries 是最好的选择,那么仅使用
RavenDB 遇到一个奇怪的问题 public ActionResult Save(RandomModel model) { //Do some stuff, validate model etc.
有没有办法保存单个跟踪对象的更改,而不是 ObjectStateManager 中的所有对象,我的意思是: ObjectContext.SaveChanges(Contact) 最佳答案 也许您可以创
查看人们编写的示例,我发现很多人使用 SaveChanges 而不是使用 SaveChangesWithRetries。我认为 SaveChangesWithRetries 是最好的选择,那么仅使用
我正在尝试编写一个生成多张发票的方法。这是一所大学,其中客户在名为 Enrollments 的类(class)中与导师一起注册。通过这种方法,我试图将导师客户的月费乘以他们的佣金百分比,因为导师从
为什么 DbContext ctx 在每次 SaveChanges() 执行后处理得更快? 第一个样本: var ctx = new DomainContext(); foreach (var ite
我一直在玩 Entity Core 类,例如 DbContext,在尝试保存对象时遇到以下错误: An error occurred while saving entities that do not
场景如下 - 不同的用户通过从网页的下拉列表中选择一个值来进行更改。下拉列表包含在 DataView 中或通过构建表格。如果用户 A 对第 1 行进行了更改,它会更新数据库并在重新绑定(bind)后显
我是一名优秀的程序员,十分优秀!