使用另一个实体创建实体';s Id,但两者之间没有关系

本文关键字:实体 Id 两者之间 没有关系 另一个 创建 | 更新日期: 2023-09-27 18:24:45

我有一些实体:

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

但是,当我插入新的CatDog对象时,很难创建新的Log条目,因为它们与CatLog没有关系。

var cat = new Cat{Name = "Kitty"};
//cat.Id == 0
DbContext.Set<Log>().Add(new Log {EntityId = cat.Id, EntityType = 1}); 

但我不想在CatDogLog类中添加导航属性,因为Log表是一个系统表,与"bussines"对象没有关系。

我的例子很简单,我有may对象,我可以在一个事务中在多个地方更改其中的许多对象。所以,我想把它们都记录下来。有办法得到这个吗?也许使用DbContext类?

使用另一个实体创建实体';s Id,但两者之间没有关系

添加新的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});