C# EfCore在添加时包含相关对象
我想这样做,但entry.Entity.User为NULLC# EfCore在添加时包含相关对象,c#,.net,entity-framework,C#,.net,Entity Framework,我想这样做,但entry.Entity.User为NULL var entry = this.myContext.Verifications.Add(new DbVerification() { UserId = model.UserId, Created = DateTimeOffset.UtcNow, Method = model.VerificationType }); entry.En
var entry = this.myContext.Verifications.Add(new DbVerification()
{
UserId = model.UserId,
Created = DateTimeOffset.UtcNow,
Method = model.VerificationType
});
entry.Entity.User.FirstName = "peanut";
我可以显式地向用户加载
this.myContext.Users.First(x => x.Id == model.UserId)
但是我是否可以在不这样做的情况下以某种方式包含entry.Entity.User对象
就像我能做到一样
this.myContext.Verifications.Include(x => x.User).Where(doesntmatter);
要将用户对象包含在实体中,是否仍可以使用如上所示的context.Verifications.Add以类似的方式包含它。可以做的一件事是使用显式加载:
var entry = this.myContext.Verifications.Add(new DbVerification()
{
UserId = model.UserId,
Created = DateTimeOffset.UtcNow,
Method = model.VerificationType
});
context.Entry(entry.Entity).Reference(p => p.User).Load();// Add this line
entry.Entity.User.FirstName = "peanut";
但最后,如果内存中没有用户实体实例,则需要进行一次往返以获取用户并进行更改,因此与此相比没有太大区别:
var entry = this.myContext.Verifications.Add(new DbVerification()
{
UserId = model.UserId,
Created = DateTimeOffset.UtcNow,
Method = model.VerificationType
});
var user=this.myContext.Users.First(x => x.Id == model.UserId);
user.FirstName = "peanut";
myContext.SaveChanges();
不清楚您在问什么,而且
myContext
没有Add
方法,您是否缺少DbSet名称?是的,我缺少一个DbSet内存中的用户实体实例是什么意思?第一个示例用于在内存中使用first或default
或Find
方法将用户
混合加载。两个代码示例都可以,但关键是最后您需要转到数据库来加载用户实体哦,是的,我知道性能方面可能并不重要,但是对于代码的可维护性,第一个例子是我所需要的。Thankscecept它应该是context.Entry(Entry.entity)。Reference…:)