Initial migration source file does not contain schema for database - asp.net-web-api

I am using entity framework 6 with Web API. I have applied Enable-Migrations command in package manager console and Migration folder created with Configuration class.
I have executed Add-Migration -InitialCreate command initial migration source file created but up and down methods are empty.
so when I recreate the database no table is created except migrationhistory table. No table is created into database so my API cannot perform any POST, GET operation and getting below error message.
Exception type: System.Data.SqlClient.SqlException
Message : Invalid object name 'dbo.Template'.
Please assist me.
I have put my connection string in database.config in startup project not in Web.config of startup project reason behind this was I didn't want to start Web API when database name changes in Web.config. I have attached my Web.config snapshot.
MigrationHistory Table
Below is code for DBContext class.
public class TestDBContext : DbContext
{
public DbSet<SamlNode> SamlNodes { get; set; }
public DbSet<Template> Templates { get; set; }
private static string connectionString
{
get
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
ConnectionStringsSection connectionString = (ConnectionStringsSection)config.GetSection("database");
if (connectionString != null && connectionString.ConnectionStrings["TestDBContext"] != null)
{
return connectionString.ConnectionStrings["TestDBContext"].ConnectionString;
}
}
}
public TestDBContext()
: base(connectionString)
{
Database.SetInitializer<TestDBContext>(new CreateDatabaseIfNotExists<TestDBContext>());
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestDBContext, Migrations.Configuration>(connectionString));
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Regards,
Rashi

Related

Database still doesn't show Identity columns after Add-migration and Update-Database Done

I created a Web API with classical data layer access class ApplicationContext
public class ApplicationContext: DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{
}
public virtual DbSet<Thing> Things{ get; set; }
}
Then i successfully added a frist Initial migration and update-database for adding columns in database.
After i had to change my ApplicationContext : DbContext to ApplicationContext : IdentityDbContext in order to get default identity tables form EmtityFramworkCore.Identity into my Database.
So i executed again a Add-Migration AddedIdentityTables for a new migration with IdentityData and i got them into a new Migration, after Update-Database i successfully got Identity columns in last Snapshot of Database im Migration folder, but there were literally no identity columns in the database
What am i doing whron?

Entity Framework Core - EF Core 2.2 - 'Point.Boundary' is of an interface type ('IGeometry')

I am trying the new functionality with EF Core 2.2. It is based on the following article. "Announcing Entity Framework Core 2.2"
https://blogs.msdn.microsoft.com/dotnet/2018/12/04/announcing-entity-framework-core-2-2/
I installed the following Nuget package.
I added the following to my model.
using NetTopologySuite.Geometries;
//New as of EF.Core 2.2
//[Required]
//[NotMapped]
public Point Location { get; set; }
During my application startup I get the following error in my Database Context on the following line:
Database.EnsureCreated();
System.InvalidOperationException
HResult=0x80131509
Message=The property 'Point.Boundary' is of an interface type ('IGeometry'). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property using the NotMappedAttribute or 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Source=Microsoft.EntityFrameworkCore
You need to call UseNetTopologySuite(). Example here:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString, opts => opts.UseNetTopologySuite());
}
public DbSet<Test> Tests { get; set; }
}
public class Test
{
public int Id { get; set; }
public Point Location { get; set; }
}
I ran into this problem because I had a
if (!optionsBuilder.IsConfigured) around everything in my OnConfiguring. I had to remove this in order to get add-migrations to work.
As Kyle pointed out you need to call UseNetTopologySuite(), but I would call it during ConfigureServices like this:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddEntityFrameworkNpgsql()
.AddDbContext<MyDBContext>(opt =>
opt.UseNpgsql(Configuration.GetConnectionString("MyDBConnection"),
o=>o.UseNetTopologySuite()))
.BuildServiceProvider();
...
}
...
}

Additional column in query generated by Entity Framework

I am using EF5 and .NET 4.5 targeting an Oracle 11g database through Oracle.ManagedDataAccess.Client. I set up a small table to test and the how it works.
Now here is a weird fact which shows no result on searching the web nor this site. On every query I have a last column like "Extent1"."Text_TextID"!!! This obviously makes Oracle to throw an error Invalid identifier as I have no column with such name nor another object in the database.
This happens no matter how many tables/columns I have and no matter how I name them (if I have several tables all will have this extra column in the query).
Anybody has any idea why this happens??
Sample code below:
//POCO class and mapping
[Table("LO_USERS")]
public class User
{
[Key]
[Column("USER_ID")]
public int UserID { get; set; }
}
//define the context
public class TestContext : DbContext
{
public TestContext():base("OracleConn")
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//replace the annoying dbo schema name. Note: even if I remove this, I still get the extra column in the query
modelBuilder.Entity<User>().ToTable("LO_USERS", "TEST_SCHEMA");
}
//create a new user
using (var db = new TestContext())
{
var user = new User();
db.Users.Add(user);
//here I set a breakpoint
db.SaveChanges();
}
The query as showing by VS2012 at the breakpoint:
SELECT
1 AS "C1",
CAST( "Extent1"."USER_ID" AS number(10,0)) AS "C2",
"Extent1"."Text_TextID" AS "Text_TextID"
FROM "TEST_SCHEMA"."LO_USERS" "Extent1"
Edit:
It is the same with EF6 and DotConnect.
I found it: the problem was I was referencing User class in another class as child object, like
public class Text
{
public virtual ICollection<User> Users { get; set; }
without specifying any foreign key column in user class and EF was trying to set one by its own.
Once I removed the line above the extra column disappeared from the select statement.

Where is EF creating my Database? If it is.

So I have SQLServerExpress 2008 R2 running, and Visual Studio 2010. I believe I have a SQL Server instance running (fig. 1). I have been informed that if I don't specify a connection string in my program, EF will create the database on a local SQL Server instance. It isnt. . .I'm getting the error
My Code is as follows:
In global.asax.cx:
protected void Application_Start()
{
Database.SetInitializer(new DatabaseInit());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Horse.cs:
public class Horse
{
public int HorseID { get; set; }
public string Name { get; set; }
public virtual Participant Participant { get; set; }
}
Participant.cs:
public class Participant
{
public int ParticipantID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
public Horse Horse { get; set; }
}
MelbourneCupDbContext:
public class MelbourneCupDbContext : DbContext
{
public DbSet<Horse> Horses;
public DbSet<Participant> Participants;
}
DatabaseInit:
public class DatabaseInit : DropCreateDatabaseAlways<MelbourneCupDbContext>
{
protected override void Seed(MelbourneCupDbContext context)
{
var Horses = new List<Horse>
{
new Horse{Name="Americain"},
new Horse{Name="Jukebox Jury"},
new Horse{Name="Dunaden"}
....
};
foreach (Horse h in Horses)
context.Horses.Add(h);
context.SaveChanges();
}
}
Finally, when I try to use the database (SignUpController.cs):
private MelbourneCupDbContext dbContext = new MelbourneCupDbContext();
[HttpGet]
public ActionResult Index()
{
IEnumerable<Horse> allHorsesList = dbContext.Horses.ToList();
return View(allHorsesList);
}
I'm getting an error when I try to call the ToList that the source cannot be null.
HALP
fig 1
"If SQL Express is installed (included in Visual Studio 2010) then the database is created on your local SQL Express instance (.\SQLEXPRESS). If SQL Express is not installed then Code First will try and use LocalDb ((localdb)\v11.0) - LocalDb is included with Visual Studio 2012"
For more information : http://msdn.microsoft.com/en-us/data/jj591621.aspx
I think your are talking about EF code-first this is a quote from a good article
By convention DbContext has created a database for you.
If a local SQL Express instance is available (installed by default
with Visual Studio 2010) then Code First has created the database on
that instance If SQL Express isn’t available then Code First will try
and use LocalDb (installed by default with Visual Studio 2012) The
database is named after the fully qualified name of the derived
context, in our case that is
CodeFirstNewDatabaseSample.BloggingContext These are just the default
conventions and there are various ways to change the database that
Code First uses, more information is available in the How DbContext
Discovers the Model and Database Connection topic.
But you can always chim in to change the settings...
Here is the full article
http://msdn.microsoft.com/en-us/data/jj193542.aspx
and here
Other Ways to Change the Database
There are a number of other ways to specify which database should be
connected to. We’ll cover these in more detail in a separate post in
the future.
App.config Connection String Create a connection string in the
App.Config file with the same name as your context. DbConnection
There is a constructor on DbContext that accepts a DbConnection.
Replace the Default Convention The convention used to locate a
database based on the context name is an AppDomain wide setting that
you can change via the static property
System.Data.Entity.Database.DbDatabase.DefaultConnectionFactory.
from this article:
http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-code-first-walkthrough.aspx
Did you saw this one?
What is the connection string for localdb for version 11
Take a look at the App_Data folder. It's the default location.
"Contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information."
http://msdn.microsoft.com/en-us/library/ex526337(v=vs.100).aspx

Entity Framework Migrations not Detecting Model Change

I'm trying to start using EF Migrations with an existing database.
The startup project is an MVC 3 project and the domain objects are in a separate project of the same solution.
Here are the steps I took:
Add-Migration InitialMigration -IgnoreChanges -Verbose
Created Configuration.cs and ###_InitialMigration.cs. Had to edit Configuration.cs to add the name of my context object as it is in a separate project.
Update-Database
Added dbo.__MigrationHistory to my database
Added a new property to an existing class
private ulong? myProp;
[DataMember]
public ulong? MyProp
{
get { return myProp; }
set
{
if (myProp != value)
{
myProp = value;
RaisePropertyChanged(() => this.MyProp);
}
}
}
Successfully compiled the solution.
Add-Migration MyNewMigration
Created ###_MyNewMigration.cs, with no migrations in it:
public partial class MyNewMigration : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Not looking good... where are the migrations?
Update-Database -Verbose -Script
No mention of the new property in the upgrade script
INSERT INTO [__MigrationHistory] ([MigrationId], [CreatedOn], [Model], [ProductVersion])
VALUES ('201206122137444_MyNewMigration', '2012-06-12T22:07:49.170Z', 0x1F8B080YadaYada, '4.3.1')
How can I get EF Migrations to pick up the model change?
It turns out that EF Migrations does not like the ulong? data type I used. That property was ignored without any warning.
Changing the type to long? allowed the migration to succeed.

Resources