Why DbContext doesn't implement IDbContext interface?

前端 未结 4 856
暖寄归人
暖寄归人 2020-12-24 10:22

Why there is no IDbContext interface in the Entity Framework? Wouldn\'t it be easier to test things if there was an existing interface with methods like SaveCha

4条回答
  •  无人及你
    2020-12-24 11:11

    I see this IDbContext:

    See this link And then you make a new partial class for your Entities Context With That interface.

    public partial class YourModelEntities : DbContext, IDbContext 
    

    EDITED: I edited this post, This Works for me. My Context

    namespace dao
    {
        public interface ContextI : IDisposable
        {
            DbSet Set() where TEntity : class;
            DbSet Set(Type entityType);
            int SaveChanges();
            IEnumerable GetValidationErrors();
            DbEntityEntry Entry(TEntity entity) where TEntity:class;
            DbEntityEntry Entry(object entity);
            string ConnectionString { get; set; }
            bool AutoDetectChangedEnabled { get; set; }
            void ExecuteSqlCommand(string p, params object[] o);
            void ExecuteSqlCommand(string p);
        }
    }
    

    YourModelEntities is your auto-generated partial class, and your need to create a new partial class with the same name, then add your new context interface, for this example is ContextI

    NOTE: The interface hasn't implement all methods, because the methods are implemented in your auto-generate code.

    namespace dao
    {
        public partial class YourModelEntities :DbContext, ContextI
        {
            public string ConnectionString
            {
                get
                {
                    return this.Database.Connection.ConnectionString;
                }
                set
                {
                    this.Database.Connection.ConnectionString = value;
                }
            }
    
            bool AutoDetectChangedEnabled
            {
                get
                {
                    return true;
                }
                set
                {
                    throw new NotImplementedException();
                }
            }
    
            public void ExecuteSqlCommand(string p,params object[] os)
            {
                this.Database.ExecuteSqlCommand(p, os);
            }
    
            public void ExecuteSqlCommand(string p)
            {
                this.Database.ExecuteSqlCommand(p);
            }
    
            bool ContextI.AutoDetectChangedEnabled
            {
                get
                {
                    return this.Configuration.AutoDetectChangesEnabled;
                }
                set
                {
                    this.Configuration.AutoDetectChangesEnabled = value;
                }
            }
    
        }
    }
    

提交回复
热议问题