简体   繁体   中英

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.

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.

Is there any other way to use an entity, and the DbContext to do this?

Thank you.

No, you can't.

You need to supply the reference navigation property's 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.

// 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.

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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