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
Related
I updated my solution from .Net 3.1 to .Net 6. Also updated the Npgsql nuget package from 5.0.10 to 6.0.4 as part of this upgrade.
Since then, I am receiving an error "Can't cast database type character to Guid" when I try to retreive data from the database.
My mapping in the context file is
entity.Property(e => e.UserId).HasColumnName("user_id").HasColumnType("CHAR(36)");
In C# class, this property is a GUID.
Is there some mapping update with the newer version of npgsql?
EF Core has a built-in value converter which implicitly converts .NET Guid properties to text columns (see docs. Note that PostgreSQL has a full UUID type - that's a better way to store GUIDs in the database, rather than as text.
This works in EF Core 6.0.4 - if you're encountering trouble, please produce a minimal, runnable code sample and add it to your question above.
Working 6.0 code:
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
ctx.Blogs.Add(new Blog { Guid = Guid.NewGuid()});
await ctx.SaveChangesAsync();
_ = await ctx.Blogs.ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(#"Host=localhost;Username=test;Password=test")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
[Column(TypeName = "CHAR(36)")]
public Guid Guid { get; set; }
}
I am experimenting with Visual Studio 2022 and EF Core 6. I created a solution with three projects, one with my razor pages one with my dbcontext and one with my entity. I was able to get the migration working with no issue, creating the database and single table which to me indicates I have everything working properly, but when I go to add a razor page and allow VS to wire up a "List" template for me, it spins for a minute and gives me an error: A type with the name Scaffolding.Entities.EncylopediaEntry does not exist.
Here is the class that apparently doesn't exist
using System.ComponentModel.DataAnnotations;
namespace Scaffolding.Entitites
{
public class EncylopediaEntry
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
And here is the DbContext with a hard coded connection string for now as I'm trying to figure out why scaffolding isn't working
using Microsoft.EntityFrameworkCore;
using Scaffolding.Entitites;
namespace ScaffoldingTest.Data
{
public class ScaffoldingContext : DbContext
{
public DbSet<EncylopediaEntry> encyclopediaEntries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("{remove}");
}
}
}
I'd got same error. Visual Studio 2022 (preview too) with NET 6.0.
I installed NET 5.0 and tested with new project net 5 then works well.
But not with NET 6.0.
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
I created Xamarin.Forms Windows UWP and Android application with shared project.
To both(UWP and Android) I imported latest stable NuGet packages:
Microsoft.EntityFramework version 1.0.0, Microsoft.EntityFramework.Sqlite version 1.0.0 and Xamarin.Forms 2.3.1.114.
On shared project I created very simple data model:
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Notes { get; set; }
}
and very simple data context:
public class DataDbContext: DbContext
{
public static string DatabasePathName;
public DataDbContext()
: base()
{
}
public DataDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(
String.Format("Filename={0}", DataDbContext.DatabasePathName));
base.OnConfiguring(optionsBuilder);
}
}
(The model uses, according to docs.efproject.net, an implicit definition of the field Id as the key and autoincrement.)
Now I initialize database: First set the platform dependent property DatabasePathName and second I'll add three User items to each. I assume that the values of these records will later be read from Resources. At this point, it is just I enter as literals. Records are saved by SaveChanges() method(both UWP and Android returns 3 (saved records)).
Now, if I run Windows UWP application and retrive these records by:
List<User> users = dbContext.Users.ToList();
and everything is as it should be. I read the records, so do I get a value which I put in a TextBlock control.
But if I use the same code in Xamarin Android Application, this code throws System.NotImplementedException exception.
I don't know why. Thank you for the advice.
There are still a few known issues with Xamarin's implementation of the .NET Standard. See aspnet/Microsoft.Data.Sqlite#255 for more details. We'll keep that issue up-to-date as Xamarin lights up.
I have problem adding entity framework model to my project. Here is what I am doing:
1- Right click on project
2- Select add
3- In dialog select data from installed templates.
4- in installed template I cannot see ADO.NET entity framework template.
What should I install?
I use NuGet to install Entity framework 4.2.0.0 but no success.
I am using Visual Studio 2010
EDIT: Look for in the comment of answer for information.
Which method of Entity Framework are you trying to use? The most straightforward (in my opinion) is CodeFirst.
DataBaseFirst or ModelFirst
If you are using the wizard to create a model,
Right-click the project > Add New Item
In whichever language you are using, there should be a Data node. Under that node, select ADO.NET Entity Data Model.
Use the designer or wizard to model your ORM mapping
CodeFirst
(you can do this with an existing database, so the name is a bit of a misnomer)
Right-click the project > Add Class
Name it for one of your planned business objects (if using an existing database, classes can be mapped by name if they match tables in the database exactly)
Outline properties (if using an existing database, properties can be mapped by name if they match fields in the database exactly)
Right-Click on the project > Add Library Package Reference
Under Online>All search for Entity, and install the Entity Framework package (if already installed, it may just need to be referenced.
You may need to resolve using statements (or include if using VB.NET) in your entity class(es).
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace Kiersted.Keps.BusinessObjects
{
[Table("Search", Schema = "mySchema")]
public class BatchSearch : KepsBusinessObject, IKepsBusinessObject
{
public BatchSearch() { }
public BatchSearch(DateTime created)
{
this.Created = created;
}
#region Data Properties
[Key]
[Column("BatchSearchID")]
public int SearchId{ get; set; }
[Column("uidQueueMaster")]
public Nullable<int> uidQueueMaster { get; set; }
[Column("DateCreated")]
public DateTime Created { get; set; }
[Column("DateCompleted")]
public Nullable<DateTime> Completed{ get; set; }
public string QueryTerms { get; set; }
[NotMapped]
public string LocalProperty { get; set; }
}
}
Note: If you are using an existing database, you can either name your classes the same as your tables or add the Table attribute to the class declaration. If you are putting your tables into a different schema (default is dbo) then you will need the Table tag regardless of the name so that you can specify the schema.
Note: If you are using and existing database, you can either name your properties the same as the corresponding fields or you can add the Column attribute.