Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否可以在不知道主键的情况下从DbContext获取具有导航属性的实体_C#_Entity Framework - Fatal编程技术网

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

C# 是否可以在不知道主键的情况下从DbContext获取具有导航属性的实体,c#,entity-framework,C#,Entity Framework,使用EF 6.1,我希望能够从DbContext返回一个实体,并填充其导航属性,而不知道主键 例如,实体: public class MyEntity { public int SomeSortOfPrimaryKey { get; set; } public string SomeProperty { get; set; } public virtual SomeOtherEntity SomeOtherEntity { get; set; } } 我有一个实体的实例

使用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();
// 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();
当您提供有效的引用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();
// 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:除非它是集合导航属性。

我这样做时的错误。Findentity:仅支持标量类型,如System.Int32、System.Decimal、System.DateTime和System.Guid。实体的实例来自何处?它可以根据需要手动创建,也可以更常用于DbContext.Entry。