我有一些实体:
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
对象时,很难创建新的日志条目,因为它们与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”对象无关。 / p>
我的例子是simlyfied,我有可能是对象,我可以在一个事务中在很多地方改变它们中的许多。所以,我想记录所有这些。
有没有办法得到这个?也许使用DbContext
类?
答案 0 :(得分:1)
添加新猫后,保存更改,然后使用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});