简体   繁体   English

实体框架按ID发行设置导航属性

[英]Entity Framework Setting Navigation Property by Id Issue

I have two classes: Owner and Dog . 我有两个班级: OwnerDog In the Dog class there is a Navigation Property defined like this: Dog类中,有一个Navigation属性定义如下:

public class Dog {
    //Other properties
    public int OwnerId { get; set; }
    [ForeignKey("OwnerId")]
    public virtual Owner Owner{ get; set; }
}

I also have the following (example) method 我也有以下(示例)方法

public void SetOwnerOfFirstDog(int ownerId)
{
   //var owner = context.Owners.First(e => e.Id == ownerId);

   var dog = context.Dogs.First();
   dog.OwnerId = ownerId;
   context.SaveChanges();
} 

This all works but when I later use the same db context and look up the same dog entity it's Owner property is null. 所有这些都有效,但是当我以后使用相同的数据库上下文并查找相同的狗实体时,其Owner属性为null。 (When I use another db context it is not null.) (当我使用另一个数据库上下文时,它不为空。)

However, if I uncomment the first line in the SetOwnerOfFirstDog method the Owner property will be correctly set. 但是,如果我取消注释SetOwnerOfFirstDog方法的第一行,则将正确设置Owner属性。 But of course this is an extra query to the database and I'd like to avoid it. 但这当然是对数据库的额外查询,我想避免这种情况。

So my question: How can I make sure that the Owner property is correctly filled in when I look it up after I have set the Dog's Owner by Id. 因此,我的问题是:在通过ID设置Dog's Owner之后,如何确保在查找时正确填写了Owner属性。

I am using lazy loading. 我正在使用延迟加载。

You can use Include to load related entities 您可以使用Include来加载相关实体

public void SetOwnerOfFirstDog(int ownerId)
{       
   var dog = context.Dogs.Include(x => x.Owner).First();
   dog.OwnerId = ownerId;
   context.SaveChanges();
} 

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

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