简体   繁体   English

添加时EfCore包含相关对象

[英]EfCore Include Related object on Add

I want to do this, but entry.Entity.User is NULL. 我想这样做,但是entry.Entity.User为NULL。

var entry = this.myContext.Verifications.Add(new DbVerification()
        {
            UserId = model.UserId,
            Created = DateTimeOffset.UtcNow,
            Method = model.VerificationType
        });
entry.Entity.User.FirstName = "peanut";

I can explicitly load the user with 我可以显式加载用户

this.myContext.Users.First(x => x.Id == model.UserId)

but can i Include the entry.Entity.User object somehow without doing this ? 但是我可以以某种方式包括entry.Entity.User对象而不这样做吗?

Just like I can do this 就像我可以做到

this.myContext.Verifications.Include(x => x.User).Where(doesntmatter);

to include the user object in the entity, is there anyway to include it in a similiar way using context.Verifications.Add as shown above. 要将用户对象包含在实体中,是否仍可以使用context.Verifications.Add以类似的方式将其包含在实体中,如上所示。

One thing you could do is use Explicit Loading : 您可以做的一件事是使用“ 显式加载”

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";

But at the end if you don't have the user entity instance in memory you're going to need to do a round trip to fetch the user and make the change, so there is not much difference compared with this: 但是最后,如果您的内存中没有用户实体实例,则需要进行往返操作以获取用户并进行更改,因此与之相比没有太大区别:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM