我有一些实体:
class Cat
{
public long Id {get;set;}
public string Name {get;set;}
}
class Dog
{
public long Id {get;set;}
public string Name {get;set;}
}
class Log
{
public long EntityId {get;set;} // cat Id, or dog Id
public int EntityType {get;set;} //cat or dog
public string Payload {get;set;} //some information
}
我想为每个插入和更新操作创建新的Log
条目。当我有猫或狗的Id时,在更新声明中很容易做到这一点。
var cat = GetCatFromDb();
//cat.Id != 0
UpdateCat(cat);
DbContext.Set<Log>().Add(new Log {EntityId = cat.Id, EntityType = 1});
但是,当我插入新的Cat
或Dog
对象时,很难创建新的Log条目,因为它们与Cat
和Log
没有关系。
var cat = new Cat{Name = "Kitty"};
//cat.Id == 0
DbContext.Set<Log>().Add(new Log {EntityId = cat.Id, EntityType = 1});
但我不想在Cat
、Dog
或Log
类中添加导航属性,因为Log表是一个系统表,与"bussines"对象没有关系。
我的例子很简单,我有may对象,我可以在一个事务中在多个地方更改其中的许多对象。所以,我想把它们都记录下来。有办法得到这个吗?也许使用DbContext
类?
添加新的cat后,保存更改,然后使用cat Id
:
var db = new YourContext();
var cat= new Cat(){Name="New Cat"};
db.Set<Cat>().Add(cat);
db.SaveChanges();
// Here it will use inserted cat Id
// MessageBox.Show(cat.Id.ToString());
db.Set<Log>().Add(new Log {EntityId = cat.Id, EntityType = 1});