简体   繁体   English

是否可以在不知道主键的情况下从DbContext获取具有导航属性的实体

[英]Is it possible to get entity with navigation properties from DbContext without knowing primary key

Using EF 6.1 I want to be able to return a single entity from the DbContext, with its navigation properties populated, without knowing the primary key. 使用EF 6.1,我希望能够从DbContext返回单个实体,并填充其导航属性,而无需知道主键。

So for example the entity: 因此,例如实体:

public class MyEntity
{
    public int SomeSortOfPrimaryKey { get; set; }
    public string SomeProperty { get; set; }
    public virtual SomeOtherEntity SomeOtherEntity { get; set; }
}

I have an instance of the entity available so I have tried: 我有可用的实体实例,所以我尝试了:

var entityWithNavProps = _dbContext.Entry(entity).Entity;

But this doesn't get the entity with it's navigation properties. 但这并不能获得具有其导航属性的实体。 Obviously the .Find() method doesn't work either as it's expecting a string, guid or integer. 显然.Find()方法也不起作用,因为它期望使用字符串,guid或整数。

Is there any other way to use an entity, and the DbContext to do this? 还有其他使用实体的方法吗,而DbContext可以做到这一点?

Thank you. 谢谢。

No, you can't. 不,你不能。

You need to supply the reference navigation property's id. 您需要提供参考导航属性的ID。

For example, given these models. 例如,给定这些模型。

public class Book
{
    public int Id { get; set; }
    public int AuthorId { get; set; }
    public User Author { get; set; }
}
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

If you don't provide reference id or you provide invalid id, it will not load the reference. 如果您不提供参考ID或您提供的ID无效,则不会加载参考。

// AuthorId = 0 is invalid id.
var book = new Book { Id = 1, AuthorId = 0 };
db.Books.Attach(book);
db.Entry(book).Reference(b => b.Author).Load();

结果

When you provide the valid reference id, it will load the reference. 当您提供有效的参考ID时,它将加载参考。

// AuthorId = 1 is a valid id.
var book = new Book { Id = 1, AuthorId = 1 };
db.Books.Attach(book);
db.Entry(book).Reference(b => b.Author).Load();

结果

PS: Unless it's a collection navigation property. PS:除非它是集合导航属性。

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

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