【问题标题】:Is it possible to get entity with navigation properties from DbContext without knowing primary key是否可以在不知道主键的情况下从 DbContext 获取具有导航属性的实体
【发布时间】:2014-07-17 06:58:17
【问题描述】:

使用 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 吗?

谢谢。

【问题讨论】:

  • 我做.Find(entity)时的错误:只支持标量类型,例如System.Int32、System.Decimal、System.DateTime和System.Guid
  • 你的实体实例是从哪里来的?
  • 如果您愿意,可以“手动创建”,或者更常见的是来自DbContext.Entry()

标签: c# entity-framework


【解决方案1】:

不,你不能。

您需要提供参考导航属性的 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:除非它是一个collection导航属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 2022-01-17
    • 2016-12-27
    • 2019-05-30
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多