我创建了一个界面:
public interface IHasSequencer
{
decimal Id { get; set; }
string GetSequenser();
}
然后在我的模型中实现它:
[Table("CLN_CLIENTS")]
public class ClnClient : IHasSequencer
{
public string GetSequenser()
{
return "SEQ_CLN_CLIENTS";
}
[Key, Column("ID")]
public decimal Id { get; set; }
[Column("FIRSTNAME")]
public string FirstName { get; set; }
[Column("LASTNAME")]
public string LastName { get; set; }
[Column("MIDDLENAME")]
public string MiidleName { get; set; }
}
并在我的 DbContext 中添加了一些MAGIC重写 SaveChanges() 方法:
public override int SaveChanges()
{
var addedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added);
foreach (DbEntityEntry entry in addedEntries)
{
if (entry.Entity is IHasSequencer)
{
var sequencerEntity = entry.Entity as IHasSequencer;
var nextSeqVal = Database.SqlQuery<Int64>("SELECT " + sequencerEntity.GetSequenser() + ".NEXTVAL FROM DUAL").First();
sequencerEntity.Id = nextSeqVal;
}
}
return base.SaveChanges();
}
而已!现在需要排序器 ID 值的模型必须实现小接口。