2014-07-17 15 views
0

使用EF 6.1我希望能够在不知道主键的情况下从DbContext中返回单个实体并填充其导航属性。是否有可能在不知道主键的情况下从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做到这一点?

谢谢。

+0

的错误,当我做了'.Find(实体)': _Only标量类型,如System.Int32,System.Decimal,System.DateTime的,和的System.Guid,是supported_ – LiverpoolsNumber9

+1

哪儿了实例您实体从何而来? –

+0

如果你愿意,它可以是“手动创建”,或者更常见的来自'DbContext.Entry()'。 – LiverpoolsNumber9

回答

0

不,你不能。

您需要提供参考导航属性的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(); 

Result

当您提供有效的参考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(); 

Result

PS:除非它是一个集合导航财产。

相关问题