Either get local entity or attach a new one

隐身守侯 提交于 2019-12-11 02:35:12

问题


My Entity looks like this:

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

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.

Example what I want to do:

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.


回答1:


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

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;
        }
    }
}

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

The usage with your case would be like this:

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);



回答2:


I've been using EF for years and i've never used the attach mechanism, it usually only gets you into trouble.
If i look at the code i'm guessing you want to create a relationship between 2 user records but you want to optimize for performance by not querying both user records. (Personally i wouldn't care about the 20ms overhead it would cost me to get the user objects but i guess it could matter).

What EF does allow you is to create records with foreign keys without loading the foreign entity.
So you could change the following code from :

var user1 = context.Users.Find(1);
var user2 = context.Users.Find(2);
var userRelation = new UserRelation();
userRelation.FromUser = user1;
userRelation.ToUser = user2;
context.UserRelations.Add(userRelation);

to :

var userRelation = new UserRelation();
userRelation.FromUserId = 1;
userRelation.ToUserId = 2;
context.UserRelations.Add(userRelation);

Note that in my last code sample i didn't query both user objects but EF will create the UserRelation record with 2 valid foreign keys.



来源:https://stackoverflow.com/questions/50748522/either-get-local-entity-or-attach-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!