Who moved my Database property? - entity-framework

I have the following DbContext code working in a project with EF 6.1.0, yet with 6.1.1 I get complaints that Database is not static. Any suggestions:
public class DataMonitorDbContext : DbContext
{
private static readonly ImportConfig Config = ImportConfig.Read();
static DataMonitorDbContext() {
Database.SetInitializer<DataMonitorDbContext>(null);
}
public DataMonitorDbContext(string connString = null)
: base(!string.IsNullOrEmpty(connString) ? connString : ConnectionString) {
}
public DbSet<DataRecord> DataRecords { get; set; }
public DbSet<LogEntry> LogEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new DataRecordMap());
modelBuilder.Configurations.Add(new LogEntryMap());
}
private static string ConnectionString {
get {
return "Data Source=" + Config.DatabasePath;
}
}
}

Have you tried using the complete namespace?
System.Data.Entity.Database.SetInitializer<DataMonitorDbContext>(null);
If that works, then you have not included the correct namespaces, or you have a namespace conflict.

Related

Entity Framework CodeFirst, Add Dbset to DbContext, programmatically

how can i Add DbSet to my dbContext class, programmatically.
[
public class MyDBContext : DbContext
{
public MyDBContext() : base("MyCon")
{
Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());
}
//Do this part programatically:
public DbSet<Admin> Admins { get; set; }
public DbSet<MyXosh> MyProperty { get; set; }
}
][1]
i want to add my model classes by ((C# Code-DOM)) and of course i did. but now i have problem with creating DbSet properties inside my Context class ...
yes i did!..
this: https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/
And this: Create Table, Run Time using entity framework Code-First
are solution. no need to dispute with dbSets directly. it just works by do some thing like that:
public class MyDBContext : DbContext
{
public MyDBContext() : base("MyCon")
{
Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
var theList = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.Namespace == "FullDynamicWepApp.Data.Domins")
.ToList();
foreach (var item in theList)
{
entityMethod.MakeGenericMethod(item)
.Invoke(modelBuilder, new object[] { });
}
base.OnModelCreating(modelBuilder);
}
}
For those using EF Core that stubble here:
The code below is only for one table with the generic type. If you want more types you can always pass them through the constructor and run a cycle.
public class TableContextGeneric<T> : DbContext where T : class
{
private readonly string _connectionString;
//public virtual DbSet<T> table { get; set; }
public TableContextGeneric(string connectionString)
{
_connectionString = connectionString;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entityMethod = typeof(ModelBuilder).GetMethods().First(e => e.Name == "Entity");
//the cycle will be run here
entityMethod?.MakeGenericMethod(typeof(T))
.Invoke(modelBuilder, new object[] { });
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString); // can be anyone
}
}

Seeding not working in Entity Framework Code First Approach

I am developing a .Net project. I am using entity framework code first approach to interact with database. I am seeding some mock data to my database during development. But seeding is not working. I followed this link - http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx.
This is my ContextInitializer class
public class ContextInitializer : System.Data.Entity.CreateDatabaseIfNotExists<StoreContext>
{
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano" ,TotalSale = 1 });
brands.Add(new Brand { Name = "Nike" , TotalSale = 3 });
foreach(Brand brand in brands)
{
context.Brands.Add(brand);
}
base.Seed(context);
context.SaveChanges();
}
}
This is my context class
public class StoreContext : DbContext,IDisposable
{
public StoreContext():base("DefaultConnection")
{
Database.SetInitializer(new ContextInitializer());
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Brand> Brands { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
This is my brand class
public class Brand
{
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string Name { get; set; }
public int TotalSale { get; set; }
}
I searched solutions online and I followed instructions. I run context.SaveChanges as well. But it is not seeding data to database. Why it is not working?
You are taking the wrong initializer, CreateDatabaseIfNotExists is called only if the database not exists!
You can use for example DropCreateDatabaseIfModelChanges:
Solution 1)
public class ContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StoreContext>
{
You have to take care with this approach, it !!!removes!!! all existing data.
Solution 2)
Create a custom DbMigrationsConfiguration:
public class Configuration : DbMigrationsConfiguration<StoreContext>
{
public Configuration()
{
// Take here! read about this property!
this.AutomaticMigrationDataLossAllowed = true;
this.AutomaticMigrationsEnabled = false;
}
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
foreach (Brand brand in brands)
{
context.Brands.AddOrUpdate(m => m.Name, brand);
}
base.Seed(context);
context.SaveChanges();
}
}
In this way you can called( !!Before you create the DbContext or in the DbContext constructor!!):
// You can put me also in DbContext constuctor
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext , Yournamespace.Migrations.Configuration>("DefaultConnection"));
Notes:
DbMigrationsConfiguration need to know about the connection string you can provide this info in the constructor or from outside.
In Your DbMigrationsConfiguration you can configure also:
MigrationsNamespace
MigrationsAssembly
MigrationsDirectory
TargetDatabase
If you leave everything default as in my example then you do not have to change anything!
Setting the Initializer for a Database has to happen BEFORE the context is ever created so...
public StoreContext():base("DefaultConnection")
{
Database.SetInitializer(new ContextInitializer());
}
is much to late. If you made it static, then it could work:
static StoreContext()
{
Database.SetInitializer(new ContextInitializer());
}
Your code is working if you delete your existing database and the EF will create and seeding the data
Or
You can use DbMigrationsConfiguration insted of CreateDatabaseIfNotExists and change your code as follow:
First you have to delete the existing database
ContextInitializer class
public class ContextInitializer : System.Data.Entity.Migrations.DbMigrationsConfiguration<StoreContext>
{
public ContextInitializer()
{
this.AutomaticMigrationDataLossAllowed = true;
this.AutomaticMigrationsEnabled = true;
}
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
foreach (Brand brand in brands)
{
context.Brands.AddOrUpdate(m => m.Name, brand);
}
base.Seed(context);
context.SaveChanges();
}
}
StoreContext
public class StoreContext : DbContext, IDisposable
{
public StoreContext() : base("DefaultConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, ContextInitializer>());
// Database.SetInitializer(new ContextInitializer());
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Brand> Brands { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
Then any change in your seed will automatically reflected to your database

Autofac using Constructor

I use unit of work pattern with entityFramework code first. Now I want to use Autofac to register UnitOfWork, Repositories and My dbContext.
This Is my UnitOfWork code:
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public UnitOfWork(DbContext context)
{
_context = context;
Contact = new ContractRepository(context);
}
public void Dispose()
{
_context.Dispose();
GC.SuppressFinalize(_context);
}
public IContactRepository Contact { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
}
and this is my repository:
public class Repository<Entity> : IRepository<Entity> where Entity : class
{
protected readonly DbContext _noteBookContext;
public Repository(DbContext noteBookContext)
{
_noteBookContext = noteBookContext;
}
public void Add(Entity entity)
{
_noteBookContext.Set<Entity>().Add(entity);
}
}
and this is one of my repositories:
public class ContractRepository: Repository<Contact>,IContactRepository
{
public ContractRepository(DbContext noteBookContext) : base(noteBookContext)
{
}
public DbContext NotebookContext
{
get
{
return _noteBookContext;
}
}
}
and this is my db context class:
public class NoteBookContext:DbContext
{
public NoteBookContext(string connectionstring):base(connectionstring)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ContactConfig());
modelBuilder.Configurations.Add(new PhoneConfig());
modelBuilder.Configurations.Add(new PhoneTypeConfig());
modelBuilder.Configurations.Add(new GroupConfig());
base.OnModelCreating(modelBuilder);
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
Now I want to register UnitOfWork with constructor (a constructor like this: )
var uow = new UnitOfWork(new NotebookdbContext("connectionstring"));
Note that NoteBookContext is my entity framework model.
I write registration but I got Error:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
.As<DbContext>();
builder.RegisterType<UnitOfWork>()
.UsingConstructor(typeof(DbContext))
.As<IUnitOfWork>();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container container = builder.Build();
This is my error:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'DataLayer.NoteBookContext' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.String connectionstring' of
constructor 'Void .ctor(System.String)'.
Edit 2 :
after help from Cyril Durand's answer I write following registering config:
var builder = new ContainerBuilder();
builder.RegisterType<ConnectionStringProvider>().As<IConnectionStringProvider>();
builder.RegisterType<NoteBookContext>().As<DbContext>().WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
and In my code :
using (var scope = DependencyInjection.Container.BeginLifetimeScope())
{
var ConnectionString = scope.Resolve<IConnectionStringProvider>();
ConnectionString.ConnectionString = "Context";
var uw = scope.Resolve<IUnitOfWork>();
var a =uw.Contact.GetAll();
}
but I got Error again:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: An exception was thrown while invoking the
constructor 'Void .ctor(System.String)' on type 'NoteBookContext'.
can everyone help me?
The error message :
An unhandled exception of type Autofac.Core.DependencyResolutionException occurred in Autofac.dll
Additional information: None of the constructors found with Autofac.Core.Activators.Reflection.DefaultConstructorFinder on type DataLayer.NoteBookContext can be invoked with the available services and parameters:
Cannot resolve parameter System.String connectionstring of constructor Void .ctor(System.String).
tells you that Autofac can't create a NoteBookContext because it can't resolve a parameter named connectionstring of type String.
Your NoteBookContext implementation needs a connectionstring, Autofac can't know it without you telling it. When you register the NoteBookContext you will have to specify the connectionstring :
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter("connectionstring", "XXX");
Another solution with dynamic resolution and a IConnectionStringProvider interface :
public interface IConnectionStringProvider
{
public String ConnectionString { get; }
}
and registration :
builder.RegisterType<ConnectionStringProvider>()
.As<IConnectionStringProvider>()
.InstancePerLifetimeScope();
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.InstancePerLifetimeScope();
It's hard to tell without seeing error. But You don't need to use UsingConstructor.
//Make DbContext per request, if your app is web app (which has http request).
builder.RegisterType<NoteBookContext>()
.As<DbContext>().WithParameter("connectionstring","ConnectionStringValue").InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container = builder.Build();
Is there a reason you want to pass the connection string to your context? Create an interface for your unitofwork and do something like this:
public class NoteBookContext:DbContext
{
//Change connectionstring below with the name of your connection string in web.config
public NoteBookContext():base("name=connectionstring")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ContactConfig());
modelBuilder.Configurations.Add(new PhoneConfig());
modelBuilder.Configurations.Add(new PhoneTypeConfig());
modelBuilder.Configurations.Add(new GroupConfig());
base.OnModelCreating(modelBuilder);
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
And register like this:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container container = builder.Build();

dbcontext - non dbo owner

I'm using EF 5 to connect to my tables, but my tables don't have dbo as the owner. EF 5 queries insert dbo as the default owner. Can you tell me how to override this? Here are some code snippets:
public class MessageBoardContext : DbContext
{
public MessageBoardContext()
: base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MessageBoardContext, MessageBoardMigrationsConfiguration>()
);
}
public DbSet<Topic> Topics { get; set; }
public DbSet<Reply> Replies { get; set; }
}
public class MessageBoardRepository : IMessageBoardRepository
{
MessageBoardContext _ctx;
public MessageBoardRepository(MessageBoardContext ctx)
{
_ctx = ctx;
}
public IQueryable<Topic> GetTopics()
{
return _ctx.Topics; //Uses dbo.Topics here! Which I don't want.
}
}
Found it! Here is the link:
http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design
Here is a quick code snippet:
public class OrderingContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customers", schemaName: "Ordering");
}}

MVC3 + Ninject + Entity framework 4

i have this Dependency resolver
public class NinjectDependencyResolvercs : IDependencyResolver
{
private readonly IResolutionRoot resolutionRoot;
public NinjectDependencyResolvercs(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return resolutionRoot.GetAll(serviceType);
}
}
in global.asax.cs
// Ninject DI container ----------------------------------------------------------- |
public void SetupDependencyInjection()
{
// Create Ninject DI kernel
IKernel kernel = new StandardKernel();
#region Register services with Ninject DI Container
// DbContext to SqlDataContext
kernel.Bind<DbContext>()
.To<SqlDataContext>();
// IRepository to SqlRepository
kernel.Bind<IRepository>()
.To<SqlRepository>();
// IUsersServices to UsersServices
kernel.Bind<IUsersServices>()
.To<UsersServices>();
// IMessagesServices to MessagesServices
kernel.Bind<IMessagesServices>()
.To<MessagesServices>();
// IJobAdvertsServices to JobAdvertsServices
kernel.Bind<IJobAdvertsServices>()
.To<JobAdvertsServices>();
#endregion
// Tell ASP.NET MVC 3 to use Ninject DI Container
DependencyResolver.SetResolver(new NinjectDependencyResolvercs(kernel));
}
// --------------------------------------------------------------------------------- |
and class
public class SqlDataContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Profile> Profiles { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<JobAdvert> JobAdverts { get; set; }
public DbSet<Message> Messages { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Roles).WithMany(x => x.Users).Map(x =>
{
x.MapLeftKey(y => y.UserId, "UserId");
x.MapRightKey(y => y.RoleId, "RoleId");
x.ToTable("UsersInRoles");
});
base.OnModelCreating(modelBuilder);
}
}
all dependecies work fine but for DbContext to SqlDataContext is problem. If use this:
public class SqlRepository
{
private DbContext dataContext;
public SqlRepository(DbContext dataContext) {
this.dataContext = dataContext;
}
public DbSet<User> Users {
get {
return dataContext.Users;
}
}
}
then
dataContext.Users
and all others properties alert this error:
'System.Data.Entity.DbContext' does not contain a definition for 'JobAdverts' and no extension method 'JobAdverts' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)
Have anyone any idea why DI doent work for Class DbContext ?
If I understand correctly, You're injecting DbContext which doesn't have those methods/properties, as they're declared in the derived type SqlDataContext.
You need to inject the SqlDataContext. If you want to use an interface, you'll need to extract an interface from SqlDataContext.
EDIT:
Ninject binds at runtime while the errors you're getting (I presume) are at compile time. You could get around this by using the dynamic key word, but that's just working AROUND the problem.
public class SqlRepository
{
private dynamic dataContext;
public SqlRepository(DbContext dataContext) {
this.dataContext = dataContext;
}
...
}
What you need to do is change the signature to use your SqlDataContext:
public class SqlRepository
{
private SqlDataContextdata Context;
public SqlRepository(SqlDataContextdata Context) {
this.dataContext = dataContext;
}
...
}
because DbContext does not contain those methods, only your SqlContext does. and your sqlcontext is bound to DbContext at runtime.