Why am I getting "Type does not exist" error adding a new razor page using entity framework - visual-studio

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.

Related

Can't cast database type character to Guid

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

EntityFrameworkCore with SQLite on Xamarin returns System.NotImplemented

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.

IdentityDbContext<TUser> in Microsoft.AspNet.Identity.EntityFramework hide base DbContext constructors

I am using Visual Studio 2013 RTM with asp.net mvc 5 entity framework asp net identity provider
I am doing the following
public class MyContext : IdentityDbContext<MyUser>
{
public MyContext (DbCompiledModel model):base(model)
{
}
public DbSet<Foo> Foos{ get; set; }
public DbSet<Bar> Bars{ get; set; }
}
and getting a compile time error on this line
public MyContext (DbCompiledModel model):base(model)
The class IdentityDbContext has hide all the constructors of DbContext.
Are there any workaround?
IdentityDbContext has only two constructors
IdentityDbContext()
IdentityDbContext(String connectionString)
As you are inheriting the IdentityDbContext, you need to follow its available guidance. So, you cannot use DbCompiledModel to construct the context.

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

ASP.NET MVC3 Validation error

If you go to this website, http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3, you can see a tutorial where users create a movie database. I completed this tutorial with no problems, and attempted to create a new MVC application with some small changes that make the project more similar to what I want to do eventually.
Rather that create a model named Movie, I created one named Issue. Like movie, it has a few fields, but they are all different names and types. I went through the process exactly as is done in the tutorial, but whenever I try to add an issue to the database via the web UI, I get a DBEntityValidationException. I have not set any validation rules at this point in the process, so I am unsure of what the problem is.
Can someone give me some advice on fixing this so that I can add Issues to my database (as is done with movies on the online tutorial)?
Let me know if more information is needed; I am very new to this and may be lacking in details.
Here is the model code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication200.Models
{
public class Issue
{
public String id { get; set; }
public DateTime created { get; set; }
public DateTime closed { get; set; }
public String summary { get; set; }
public bool? importToTFS { get; set; }
}
public class IssueDBContext : DbContext
{
public DbSet<Issue> Issues { get; set; }
}
}
Update:I just redid the whole process, but rather than have different fields and different types, I made it so that my Issue model had the same number and same types of fields (with only different names). The error went away, so the problem must be with db format or something. I hope this makes the problem more clear.
I just ended up adding this class, which removes everything from the database when fields are changed. Then, I refresh the database, which is easy to do in my situation. One could add some items to the Seed method in order to ensure that some things remain in the updated database after it is cleared.
public class IssueInitializer : DropCreateDatabaseIfModelChanges<IssueDBContext>
{
protected override void Seed(IssueDBContext context)
{
//add things here
}
}

Resources