I have a little problem with publishing my application.
Here's the DbContext:
public class UsersDb : DbContext
{
public DbSet<Users> Users { get; set; }
public DbSet<Locations> Locations { get; set; }
}
When i'm publishing my application, all tables (Users and __MigrationHistory) are creating on SQL server database, but Locations table isn't.
I'm trying to use Package/Publish SQL tab in project properties, but got and error
Error MSB4018: The "SqlScriptPreprocessSqlVariables" task failed unexpectedly
Also tried to use several DbContexts but with no luck. Locations table was still not created.
Related
Currently looking at the Enable Offline Sync for Xamarin Form : https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-forms-get-started-offline-data.
I am having the code running on mobile and the backend run and created ToDoList table with 2 entries. The table created in ToDoList has UpdateAt, Version and Deleted columns create from the controller which extends TableController.
In existing web application currently already using the database with tables, do I have to create all the tables with UpdateAt, Version and Deleted columns. I am unsure how this data generated for those columns in web application so that both mobile and web data can be consistent.
This free online book will go through details of getting the backend setup.
https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter3/dataconcepts/
One of the ways described is to you EF already built in Code-First with migrations, and have a base class that looks like this
public abstract class TableData
{
public string Id { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public byte[] Version { get; set; }
}
Those are the table properties missing you asked about.
I'm trying to use EF6 in my project and I've got two databases I'm trying to interact with. My app.config has connection strings for both, and I have two DbContext classes that pass in the app.config's key for the corresponding connection string. One context:
public LogProcessorContext() : base("LogProcessorDb")
{
}
public DbSet<LogFile> LogFiles { get; set; }
the other context:
public MessageTrackingContext() : base("MessageTrackingDb")
{
}
public DbSet<JournalLog> JournalLogs { get; set; }
but when I add the migration using add-migration NewBranch and update the db, a log file table gets added to the message tracking db (the wrong one), and the journallogs table doesn't get added at all. If anyone has any experience getting ef to play nice with multiple db/contexts, i'm all ears. I'm sure its just some simple mistake I'm making.
btw,
"LogProcessorDb"
and
"MessageTrackingDb"
are the keys in my app.config for my connection strings.
Thanks!
I have deployed a database file for a xamarin project using the following guide. http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/
I created a model class as such:
[Table ("Person")]
public class Person
{
[PrimaryKey, AutoIncrement, Column("Id")]
public int Id { get; set; }
[NotNull, Column("Actor_Id")]
public int ActorId { get; set; }
}
When I try to do an insert in the repository
dbConn.Insert(newPerson);
I'm getting SQLite.Net.SQLiteException: table Person has no column named ActorId.
If the column name in the database is Actor_Id shouldn't the [Column] attribute in the model map it to the table.
There is a chance that your phone/emulator is previously deployed with app that with older database schema.
In this case, you will need to:
Remove the existing app in your phone/emulator. Then the next run should be OK due to it is created using new database schema. OR
Perform database upgrade script to change the schema of the current old database. Only do this if your app is already publish to store.
I found the problem to be that I was using the SQLite library in the model. Changing it to use SQLite.Net.Attributes allowed the correct mapping.
using SQLite.Net.Attributes;
I have a bunch of problems trying to enable (code-first) migrations for my SQL Server Compact 4.0 database for my desktop .NET app.
Enable-Migrations does work and the directory Migrations is created. After that when I try to run Add-Migration InitialMigration, I get:
Access to the database file is not allowed. [ 1914,File name = Logo.sdf,SeCreateFile ]
This is the first problem, but I solved it by running Visual Studio as Administrator... don't like that solution and also don't know if later in production it will work without the app being run in Admin mode. I let that problem aside for now...
My connection string:
<add name="LogoContext"
connectionString="Data Source=Logo.sdf"
providerName="System.Data.SqlServerCE.4.0"/>`
So after running Add-Migration InitialMigration in Administrator mode I get an empty migration... that's ok. Then I delete the migration and add a new class:
using System;
using System.Collections.Generic;
public class Blog
{
public int ID { get; set; }
public string Title { get; set; }
}
I add a reference to the context class:
public class LogoContext : DbContext
{
public DbSet<Word> Words { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
}
Then run Add-Migration InitialMigration again and get:
public partial class InitialMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Blogs",
c => new
{
ID = c.Int(nullable: false, identity: true),
Content = c.String(maxLength: 4000),
})
.PrimaryKey(t => t.ID);
}
public override void Down()
{
DropTable("dbo.Blogs");
}
}
After running Update-Database I see:
Applying code-based migrations: [201304211225255_InitialMigration].
Applying code-based migration: 201304211225255_InitialMigration.
Running Seed method.
Now the problem appears - in my Server Explorer I examine the database Logo.sdf and it does not include the table Blogs! I even try to run this code from my app:
var db = new LogoContext();
db.Posts.Add(new Blog { Title= "moo" });
db.SaveChanges();
to check if maybe my Server Explorer isn't showing the table.. but I get an exception:
The specified table does not exist. [ Blogs ]
So the migrations are obviously not being applied to my Logo.sdf file :(
If I remove the connection string from app.config, the connection to a local instance of SQL Server Express is assumed. And there it works flawlessly!! When I examine the database with SQL Server Management Studio, I see the new Blogs table and also a system table for metadata about migrations...
Another little piece of information:
When I try to run Update-Database again, I get "No pending code-based migrations." and that tells me that some data is being saved to Logo.sdf after all... at least some metadata about migrations, but still I can't see that table in Server Explorer.
I'm using VS 2012 and EF 5.0.
Please help me understand this... It looks to me that something is seriously wrong because it just works with SQL Server Express instance, but not with SQL Server CE 4.0. :((
Thank you!
david
So the problem was that the solution created a separate .sdf file here:
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Logo.sdf"
Which was unexpected and strange IMHO...
I ended up using this connection string:
<add name="LogoContext" connectionString="Data Source=|DataDirectory|\Logo.sdf" providerName="System.Data.SqlServerCE.4.0"/>
This references bin/Debug/Logo.sdf and it works during development and when running a .exe separately.
The only thing with this way is that my Logo.sdf project file (which was getting copied to Debug "if newer") is now completely ignored. All the migrations will be run on the Debug file.. That's probably good too....
Thanx Erik for the hint!
david
I'm trying to use Code First with my local instance of Sql Server 2008 R2. I've create a user 'dev' and can log in and create databases using Sql Managment Studio. The problem is I keep getting an error message when trying to create a database using DbContext in EntityFramework. Here is the error message:
"A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified"
The error message I checked my Sql Server and it does allow remote connections.
I've abstracted my system with the following code and get the same error:
namespace CodeFirstConsole
{
public class Program
{
static void Main(string[] args)
{
var db = new MyContext();
try { Console.WriteLine(db.Parents.Count()); }
catch (Exception) { throw; }
Console.Read();
}
}
internal class MyContext : DbContext
{
public DbSet<ParentObject> Parents { get; set; }
public DbSet<ChildObject> Children { get; set; }
public MyContext()
{
this.Database.Connection.ConnectionString =
"Data Source=.;Database=ConsoleTest;Initial Catalog=ConsoleTest;User ID=dev;Password=dev;";
}
}
internal class ParentObject
{
public int Id { get; set; }
public string PropertyOne { get; set; }
}
internal class ChildObject
{
public int Id { get; set; }
public bool PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public virtual ParentObject Parent { get; set; }
}
internal class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
context.Parents.Add(new ParentObject() { PropertyOne = "hi" });
base.Seed(context);
}
}
}
I had the same error that drove me nuts for about a day. My situation was I had a large solution with a pre-existing start-up project and I was adding EF to the persistence project.
So the first step was to add the EF dependency. This created an app.config in my persistence project with the correct EF content. Then I went to Enable-Migrations and got the same error in this post. At this point I didn't think of copying the EF app.config settings to the app.config of the start-up project since I thought I'd have to play around with it before I would eventually run the app.
The problem was resolved when I changed the solution start-up project to the persistence project so I could get EF to find the correct app.config. Or I could have copied the EntityFramwework related section to the app.config of the start-up project.
Had the same error message developing on local, but it worked fine yesterday.
Turns out the wrong project in the solution was set as the StartUp Project.
So if you are also getting this message after an update-database command in the Package Manager Console, be sure to check if the correct StartUp Project is set.
For example the Web project, and not one of the helper projects.
Visual studio seems to have the habit of setting other projects as the StartUp by itself sometimes...
Try having a look here it explains a lot of the causes, since you indicated in the comments that you did explicitly specify server name and the code runs also on the same machine as sql server since from what I see the datasource just has a dot, indicating that its the same machine as the c# code program running on.
http://blogs.msdn.com/b/sql_protocols/archive/2007/05/13/sql-network-interfaces-error-26-error-locating-server-instance-specified.aspx
Had to add the EntityFramework dependency also to the startup project.
Install-Package EntityFramework
And also had to define connectionStrings to my main project App.config/Web.config.
<connectionStrings>
<add name="Database" providerName="System.Data.SqlClient" connectionString="foo.bar" />
</connectionStrings>
Here was a solution for me
Traditional SqlClient can find server instance but EF can't
In short:
Database.SetInitializer<MyContext>(
new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>(
useSuppliedContext: true));
Main part here is useSuppliedContext: true
I had the same problem and spent a whole day on it. Finally found #Christian's answer and now I find a much better way!
Put ConnectionString in the startup project. So you don't need to switch every time you change an entity.