DbSet doesn't have a Find method in EF7

后端 未结 11 1779
醉话见心
醉话见心 2020-12-03 04:28

I am trying to create a generic repository to access my database. In EF6 I was able to do that in order to get a specific entity:

protected IDbSet d         


        
11条回答
  •  孤城傲影
    2020-12-03 05:01

    In case you are using EF 7.0.0-rc1-final, below you find a small update for the code presented by @bricelam in the previous answer. By the way, thank you very much @bricelam - your code was extremely useful for me.

    Here are my dependencies under "project.config":

    "dependencies": {
        "EntityFramework.Commands": "7.0.0-rc1-final",
        "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
        "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
        "Microsoft.Framework.ConfigurationModel": "1.0.0-beta4",
        "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
        "Microsoft.Framework.DependencyInjection": "1.0.0-beta8"
    }
    

    And below is the extension method for DbSet.Find(TEntity):

    using Microsoft.Data.Entity;
    using Microsoft.Data.Entity.Infrastructure;
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    
    namespace Microsoft.Data.Entity.Extensions
    {
        public static class Extensions
        {
            public static TEntity Find(this DbSet set, params object[] keyValues) where TEntity : class
            {
                var context = ((IInfrastructure)set).GetService();
    
                var entityType = context.Model.FindEntityType(typeof(TEntity));
                var key = entityType.FindPrimaryKey();
    
                var entries = context.ChangeTracker.Entries();
    
                var i = 0;
                foreach (var property in key.Properties)
                {
                    entries = entries.Where(e => e.Property(property.Name).CurrentValue == keyValues[i]);
                    i++;
                }
    
                var entry = entries.FirstOrDefault();
                if (entry != null)
                {
                    // Return the local object if it exists.
                    return entry.Entity;
                }
    
                // TODO: Build the real LINQ Expression
                // set.Where(x => x.Id == keyValues[0]);
                var parameter = Expression.Parameter(typeof(TEntity), "x");
                var query = set.Where((Expression>)
                    Expression.Lambda(
                        Expression.Equal(
                            Expression.Property(parameter, "Id"),
                            Expression.Constant(keyValues[0])),
                        parameter));
    
                // Look in the database
                return query.FirstOrDefault();
            }
        }
    }
    

提交回复
热议问题