覆盖SaveChanges()的最佳方法 [英] Best way to override SaveChanges()

查看:95
本文介绍了覆盖SaveChanges()的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在一个项目上工作了1个月,有6个实体与其他实体没有任何关系。它们都是简单的实体。



我们为每个实体上的操作创建了6个不同的类。 SaveOrUpdateEntity()类的方法与您认为的几乎相同。就像这样:

 公共静态ErrorType SaveOrUpdateEntity(EntityEntity,int userID)
{
尝试
{
使用(DataEntities ctx = new DataEntities())
{
if(entity!= null)
{
if(entity.entityID == 0)
{
entity.CreateDate = DateTime.Now;
实体.CreatedBy =用户ID;

ctx.Entry(entity).State = EntityState.Added;
}
else
{
entity.ModifyDate = DateTime.Now;
实体。ModifiedBy =用户ID;

ctx.Entry(entity).State = EntityState.Modified;
}
}

ctx.SaveChanges();
}

返回ErrorType.NoError;
}
catch(异常例外)
{
return ErrorType.SaveError;
}
}

如果<$ c $通过覆盖 SaveChanges()方法,c> SaveOrUpdateEntity()方法更短,更通用。根据有关覆盖 SaveChanges()方法的其他问题,文章和帖子,实现存储实体状态的接口是一个很好的解决方案,但我也想知道其他解决方案。 p>

因为我是新手,所以所有答案都将不胜感激。



谢谢。

解决方案

您可以执行以下操作



1-在应用程序中创建一个包含所有类的接口具有以下属性的对象将实现此接口:Id,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy

 公共接口ITrack 
{
int Id {get; set;}
int CreatedBy {get; set;}
DateTime CreatedDate {get; set;}
int? ModifiedBy {get; set;} // int?因为在第一次添加时,没有修改
DateTime吗?通过{get;设置;}
}




最佳做法 CreatedBy ModifiedBy 定义为 string


2-将添加一个类 TrackableEntry 实现接口 ITrack

 公共抽象类TrackableEntry:ITrack 
{
public int Id {get; set;}
public int CreatedBy {get; set;}
public DateTime CreatedDate {get; set;}
public int? ModifiedBy {get; set;}
公共DateTime?通过{get; set;}
}

3-从您所有的界面中删除界面中提到的属性类,并让这些类直接从 TrackableEntry

 公共类A实现:TrackableEntry 
{
// public int ID {get; set;}
// public int CreatedBy {get; set;}
//公共DateTime CreatedDate {get; set;}
// public int? ModifiedBy {get; set;}
//公共DateTime?通过{get; set;}
}

4-在您的 DbContext中文件覆盖您的 SaveChanges 并添加属性 UserId UserName 如果您遵循 *最佳做法* 部分

  public int UserId {get; set;} 

公共重写int SaveChanges()
{
this.ChangeTracker.DetectChanges();
var add = this.ChangeTracker.Entries()
.Where(t => t.State == EntityState.Added)
.Select(t => t.Entity)
.ToArray();

foreach(添加的var实体)
{
如果(实体为ITrack)
{
var track =实体为ITrack;
track.CreatedDate = DateTime.Now;
track.CreatedBy = UserId;
}
}

varmodified = this.ChangeTracker.Entries()
.Where(t => t.State == EntityState.Modified)
.Select(t => t.Entity)
.ToArray();

foreach(已修改的变量实体)
{
如果(实体为ITrack)
{
var track =实体为ITrack;
track.ModifiedDate = DateTime.Now;
track.ModifiedBy = UserId;
}
}
返回base.SaveChanges();
}

最后在您要调用 SaveChanges时在表单中方法,请确保设置 UserId UserName

  varentity = new Entities(); //假设您的DbContext文件名为Entities 
//用于在此处添加或删除或修改
实体的代码。As.Add(new A(){...});

// ....

entities.UserId = MyUser;
entities.SaveChanges();

希望这对您有帮助


We have worked on a project for 1 month and there are 6 entities without any relationship with other entities. They are all simple entities.

We have created 6 different classes for operations on each entity. SaveOrUpdateEntity() methods of classes are almost same as you think. It is something like that:

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;
    }
}

It would be very helpful, if SaveOrUpdateEntity() method is shorter and more generic by overriding SaveChanges() method. According to other questions, articles, and posts about overriding SaveChanges() method, implementing interface that stores state of entities is a good solution but I am also wondering other solutions.

Because I am newbie, all answers would be very appreciated.

Thank you.

解决方案

you can do the following

1- create an Interface in your application that all the classes that has the following properties will implement this 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 and ModifiedBy as string which will be good for performance and maintenance

2- Add a class TrackableEntry which implements the 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- remove the properties mentioned in the interface from all of your classes and let these classes to implement directly from 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- In your DbContext file override your SaveChanges and add property UserId or UserName if you followed the *Best practices* part

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();
}

finally in your forms when you want to call SaveChanges method, ensure you set the UserId or UserName value

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();

hope this will help you

这篇关于覆盖SaveChanges()的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆