5

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.

Pete
  • 179
  • 11

2 Answers2

6

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);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

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.

Kristof
  • 3,267
  • 1
  • 20
  • 30
  • I wrapped most database logic into repositories. Creating a function like AddRelation(int fromId, int toId) would be awful as soon I deal with two or more different Entities.Swapping the parameters on the caller side will result in a bug which is hard to find IMO. Also I forgot to point out I want an efficient way to update on single property in the relation which works kinda fine with Attach. – Pete Jun 07 '18 at 21:00