标签:
public class Context : DbContext
{
public DbSet<Person> Person { get; set; }
}
public abstract class Entity
{
public long ID
{
get;
set;
}
public abstract void OnSetDefaultValue();
public abstract void OnValidate();
public abstract void Updating();
public abstract void Updated();
public abstract void Inserting();
public abstract void Inserted();
public abstract void Deleting();
public abstract void Deleted();
}
public class Person : Entity
{
public string Name
{
get;
set;
}
public override void OnValidate()
{
}
public override void Updating()
{
}
public override void Updated()
{
}
public override void Inserting()
{
}
public override void Inserted()
{
}
public override void Deleting()
{
}
public override void Deleted()
{
}
public override void OnSetDefaultValue()
{
}
}
public class Model
{
public List<DbEntityEntry> Records
{
get;
set;
}
public void OnSave()
{
using (Context c = new Context())
{
using (TransactionScope transaction = new TransactionScope())
{
Entity entity = null;
foreach (DbEntityEntry record in Records)
{
if (record != null)
{
entity = record.Entity as Entity;
if (entity != null)
{
switch (record.State)
{
case EntityState.Added:
entity.OnSetDefaultValue();
entity.OnValidate();
entity.Inserting();
c.Set(record.Entity.GetType()).Add(entity);
entity.Inserted();
break;
case EntityState.Modified:
entity.OnSetDefaultValue();
entity.OnValidate();
entity.Updating();
c.Set(record.Entity.GetType()).Attach(entity);
entity.Updated();
break;
case EntityState.Deleted:
entity.Deleting();
c.Set(record.Entity.GetType()).Remove(entity);
entity.Deleted();
break;
}
}
}
}
c.SaveChanges();
transaction.Complete();
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/MyCSharpLiujunjie/p/5568268.html