[英]Is it possible to get entity with navigation properties from DbContext without knowing primary key
使用EF 6.1,我希望能夠從DbContext返回單個實體,並填充其導航屬性,而無需知道主鍵。
因此,例如實體:
public class MyEntity
{
public int SomeSortOfPrimaryKey { get; set; }
public string SomeProperty { get; set; }
public virtual SomeOtherEntity SomeOtherEntity { get; set; }
}
我有可用的實體實例,所以我嘗試了:
var entityWithNavProps = _dbContext.Entry(entity).Entity;
但這並不能獲得具有其導航屬性的實體。 顯然.Find()
方法也不起作用,因為它期望使用字符串,guid或整數。
還有其他使用實體的方法嗎,而DbContext可以做到這一點?
謝謝。
不,你不能。
您需要提供參考導航屬性的ID。
例如,給定這些模型。
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; }
}
如果您不提供參考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();
當您提供有效的參考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:除非它是集合導航屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.