使用其他实体的ID创建实体但

时间:2015-11-28 11:10:25

标签: c# entity-framework

我有一些实体:

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对象时,很难创建新的日志条目,因为它们与CatLog没有关系。

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

但我不想将导航属性添加到CatDogLog类,因为Log表是系统表,与“bussines”对象无关。 / p>

我的例子是simlyfied,我有可能是对象,我可以在一个事务中在很多地方改变它们中的许多。所以,我想记录所有这些。 有没有办法得到这个?也许使用DbContext类?

1 个答案:

答案 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}); 
相关问题