简体   繁体   English

Entity Framework Core(7):通过id加载单个实体

[英]Entity Framework Core (7): load single entity by id

.ToListAsync is used to get a collection of items from DB in EF Core. .ToListAsync用于从 EF Core 中的 DB 获取项目集合。 That's clear.这很清楚。 But what is the right way to get single item?但是获得单个物品的正确方法是什么? In async way if possible.如果可能,以异步方式。

public async static Task<Source> LoadEntityAsync(int sourceID)
{
    using (var db = new RPDBContext())
    {
        var sources =
            await
                db.Source
                    .Where(x => x.SourceID == sourceID)
                    .ToListAsync();
        // TODO that's like a hack:
        return sources.First();
    }
}

You should use SingleOrDefaultAsync if you want the object to be unique.如果您希望对象是唯一的,您应该使用SingleOrDefaultAsync If you know that the object is unique from domain restrictions or if you are accessing it through primary key then you can use FirstOrDefaultAsync .如果您知道该对象在域限制中是唯一的,或者您通过主键访问它,那么您可以使用FirstOrDefaultAsync

var sources = await db.Source
            .Where(x => x.SourceID == sourceID)
            .SingleOrDefaultAsync();

you can use another overload and shorten the query您可以使用另一个重载并缩短查询

var sources = await db.Source
            .SingleOrDefaultAsync(x => x.SourceID == sourceID);

same rules apply to FirstOrDefaultAsync .相同的规则适用于FirstOrDefaultAsync

If you want to ensure that the object exists just remove the OrDefault part and use SingleAsync and FirstAsync .如果要确保对象存在,只需删除OrDefault部分并使用SingleAsyncFirstAsync

If you need to retrieve a single item, use FirstOrDefaultAsync :如果您需要检索单个项目,请使用FirstOrDefaultAsync

public static Task<Source> LoadEntityAsync(int sourceID)
{
    using (var db = new RPDBContext())
    {
        return db.Source.FirstOrDefaultAsync(x => x.SourceID == sourceID);
    }
}

The approved answer is correct, but not the best from my point of view.批准的答案是正确的,但从我的角度来看不是最好的。

If you are searching by the id, use the Find(PropertyID) method like this:如果您按 id 搜索,请使用 Find(PropertyID) 方法,如下所示:

db.Source.Find(SourceID) db.Source.Find(SourceID)

where:在哪里:

  • db: database context db:数据库上下文
  • Source: your entity type来源:您的实体类型
  • SourceId is the Primary key SourceId 是主键

It returns the object or null, if not found.如果未找到,则返回对象或 null。 More details here: https://docs.microsoft.com/en-us/ef/ef6/querying/#:~:text=The%20Find%20method%20on%20DbSet,context%20or%20in%20the%20database .此处有更多详细信息: https : //docs.microsoft.com/en-us/ef/ef6/querying/# :~: text=The%20Find%20method%20on%20DbSet,context%20or%20in%20the%20database

If you are using async method please make sure using Await keyword before calling it For exmaple :如果您使用异步方法,请确保在调用之前使用 Await 关键字例如:

await _userProfileRerpository.GetByIdentityIdAsync(CurrentUserIdIdentity);

In my case i am not getting the proper entity value after use of await keyword it fixed在我的情况下,在使用它修复的 await 关键字后,我没有获得正确的实体值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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