获取本地实体或附加一个新实体 [英] Either get local entity or attach a new one

查看:34
本文介绍了获取本地实体或附加一个新实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体如下所示:

public class User
{
    public int Id {get; set;}
}

我不想在每次获得特定用户时查询数据库,其中我知道此 ID 存在用户.似乎附加适用于这种情况,但如果 DbContext 已经在本地存储了该特定用户的实体,它将引发异常.

I don't want to query the database each time I have get a specific User where I know a User exists for this Id. Seems like Attach works for this case but If the DbContext already stores the Entity for this specific User locally It will throw an exception.

例如我想做什么:

var user1 = ctx.GetLocalOrAttach(new User{Id = 1});
var user2 = ctx.GetLocalOrAttach(new User{Id = 2});
AddUserRelation(user1, user2);

有什么解决办法吗?如果不是,那么检查本地是否存在实体的理想方法是什么.

Is there some solution for this? If not what would be the ideal way to check if an Entity exists locally.

推荐答案

您可以搜索 DbSet<T>.Local 属性,但这会效率低下.

You can search the DbSet<T>.Local property, but that would be inefficient.

IMO 更好的方法是使用我对 在EntityFrameworkCore中根据ID删除加载和卸载的对象

A better way IMO is to use the FindTracked custom extension method from my answer to Delete loaded and unloaded objects by ID in EntityFrameworkCore

using Microsoft.EntityFrameworkCore.Internal;

namespace Microsoft.EntityFrameworkCore
{
    public static partial class CustomExtensions
    {
        public static TEntity FindTracked<TEntity>(this DbContext context, params object[] keyValues)
            where TEntity : class
        {
            var entityType = context.Model.FindEntityType(typeof(TEntity));
            var key = entityType.FindPrimaryKey();
            var stateManager = context.GetDependencies().StateManager;
            var entry = stateManager.TryGetEntry(key, keyValues);
            return entry?.Entity as TEntity;
        }
    }
}

类似于 EF Core Find 方法,但如果实体在本地不存在,则不会从数据库中加载该实体.

which is similar to EF Core Find method, but does not load the entity from the database if it doesn't exist locally.

您的案例的用法如下:

var user1 = ctx.FindTracked(1) ?? ctx.Attach(new User { Id = 1 }).Entity;
var user2 = ctx.FindTracked(2) ?? ctx.Attach(new User { Id = 2 }).Entity;
AddUserRelation(user1, user2);

这篇关于获取本地实体或附加一个新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆