Entity Framework Core migrations empty on creation - entity-framework

I'm trying to create an instance of my database on an actual SQL Server rather than just locally hosted, but every time I try and create a migration they're coming back empty...
public partial class InitialMigration0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
Here is my appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server={dbName};Trusted_Connection=True;MultipleActiveResultSets=true;"
// "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MLD-1ED06986-5F07-4A1C-85B9-D9F3F477BFF5;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
And my AppDbContext:
namespace MLD.Models
{
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
//public DbSet<User> Users { get; set; }
public DbSet<LymphSite> LymphSites { get; set; }
public DbSet<Measurement> Measurements { get; set; }
public DbSet<Circumference> Circumferences { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
Any ideas why this is coming back empty? It worked fine for my localDb and it's connected to the SQL Server, but without anything coming up in the migrations it can't create tables so I'm at a bit of a loss!
Thanks in advance

Connection string solution:
I needed to add Integrated security to my connection string, user Id and password were not needed in this instance - when using User Id and password the user created did not have permissions to create database
{
"ConnectionStrings": {
"DefaultConnection": "Server={server name}; Database=Z_MyDiary;MultipleActiveResultSets=true; Integrated Security=true;"
},
Fix for migrations issue: x
Not a clue why the migrations were going wrong in the first place but they work now!

Related

Why table not exists while I create a in-memory sqlite database with entityframework core?

I want to create an in-memory SQLite database.
Here is startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<TestDBContext>().AddEntityFrameworkSqlite();
}
Here is the Model of database:
public class TestModel
{
public string UserName { get; set; }
[Key]
public string id { get; set; }
}
Here is the DBContext of database:
public class TestDBContext : DbContext
{
public virtual DbSet<TestModel> Test { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=:memory:");
}
}
And here is the controller:
private readonly TestDBContext TestDBContext;
public HomeController(ILogger<HomeController> logger,TestDBContext _TestDBContext)
{
_logger = logger;
this.TestDBContext = _TestDBContext;
}
public IActionResult Index()
{
TestDBContext.Database.EnsureCreated();
TestDBContext.SaveChanges();
TestDBContext.Test.Add(new TestModel() { User = DateTime.Now.ToString(),id=Guid.NewGuid().ToString() });
TestDBContext.SaveChanges();
return View(TestDBContext.Test.ToList());
}
Every time it runs, it will report an error:
Inner Exception 1:
SqliteException: SQLite Error 1: 'no such table: Test'.
I have used the EnsureCreated and the EnsureCreated runs without any error. Why it still be like this?
EF Core's DbContext always opens and closes connections to the database automatically, unless you pass an already open connection. And when the connection gets closed, the Sqlite In-memory database will be removed. So I modified your code a little bit like this.
public void ConfigureServices(IServiceCollection services)
{
var connection = new SqliteConnection("datasource=:memory:");
connection.Open();
services.AddControllersWithViews();
services.AddDbContext<TestDBContext>(options =>
{
options.UseSqlite(connection);
});
}
And the Database Context class - I added the constructors so that I can provide the parameters.
public class TestDBContext : DbContext
{
public TestDBContext(DbContextOptions options) : base(options)
{
}
protected TestDBContext()
{
}
public virtual DbSet<TestModel> Test { get; set; }
}
And instead of creating the database in the Index action method, create it in the startup.
Also, opt to use the DbContext.Database.Migrate() method instead of EnsureCreated else you won't be able to use migrations later down the line.

Problems creating more schemas in PostgreSQL + .NET Core

We recently created a web project in .NET Core and are using PostgreSQL via NPGSQL Entity Framework extension. At first, there were no problems at all. But when trying to add more schemas, the new schema was not created. According to other posts on the Internet, we should not be limited to any number of schemas. Does anybody know what might cause the problem?
P.S.: After dropping the original schema, the new schema was successfully created. However, trying to add next schema without dropping the previous one seems like a problem.
FooDbContext.cs
public class FooDbContext : DbContext
{
/// <summary>
/// For unit testing.
/// </summary>
public FooDbContext()
: base()
{
}
public FooDbContext(DbContextOptions<FooDbContext> options)
: base(options)
{
}
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<Project> Projects { get; set; }
public virtual DbSet<PersonOnProject> PeopleOnProjects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("TestingFoo");
base.OnModelCreating(modelBuilder);
}
}
Startup.cs
...
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFrameworkNpgsql().AddDbContext<Model.FooDbContext>((provider, builder) => {
builder.UseNpgsql(Configuration.GetConnectionString("LocalDb"), b => b.MigrationsAssembly("TestingFoo"));
});
services.AddMvc();
}
....
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.ApplicationServices.GetService<Model.FooDbContext>().Database.EnsureCreated();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404
&& !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseStaticFiles();
app.UseMvc();
}
We found we had difficulty "seeing" other schemas besides "public" until we adjusted the connection string to connect to the cluster instead of the instance.

Who moved my Database property?

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.

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

EntityCodeFirst + MVC4 WebSecurity = Sad Me

Coming from This Example
I have a data context
public class AggregateContext : DbContext
{
public DbSet<BlogEntry> BlogEntries { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
}
And in app start I have this
Database.SetInitializer(new TestingDbInitializer());
new AggregateContext().UserProfiles.Find(1);
And my Initializer looks like this
public class TestingDbInitializer : DropCreateDatabaseAlways<AggregateContext>
{
protected override void Seed(AggregateContext context)
{
AccountsContext(context);
// add a bunch of Lorems to the blog. does call context.SaveChanges();
BlogsContext(context);
}
void AccountsContext(AggregateContext context)
{
WebSecurity.InitializeDatabaseConnection(
"DefaultConnection",
"UserProfile",
"UserId",
"UserName",
autoCreateTables: true);
//create Admin
if (!WebSecurity.ConfirmAccount("Admin"))
{
var confirm = WebSecurity.CreateUserAndAccount(
"Admin",
"password",
new { Email = "please#help.me" });
if (!Roles.RoleExists("Admin"))
Roles.CreateRole("Admin");
Roles.AddUserToRole("Admin", "Admin");
}
}
When I run it I crash on this line.
var confirm = WebSecurity.CreateUserAndAccount(
"Admin",
"password",
new { Email = "please#help.me" });
with the sqlexception "Invalid column name 'Email'."
Looking at my database in server explorer I see that the email column was not created.
public class AggregateContext : DbContext
{
public AggregateContext()
: base("DefaultConnection")
{
}
public DbSet<BlogEntry> BlogEntries { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
}
Forgot to define the connection. Go Me !