SqlException: Invalid column name, how to fix? - c#

I added two new properties to my model, however when I try to run the project this error appears
How do I fis this?
Here is my model Occorrencias:
public class Ocorrencias
{
[Key]
public int Id { get; set; }
public string NomeFotografia { get; set; }
[ForeignKey("Ignicao")]
[Display(Name = "Ignicao")]
public int IgnicaoFK { get; set; }
public virtual Ignicoes Ignicao { get; set; }
}
The project runs fine but it gives me also an error saying ailed to load resource: the server responded with a status of 500 ()

This is because the properties you added to the Model does not exist in the database.
you can use add-migration to update your database:
open Package Manager Console from Tools>NuGet Package Manage in visual studio and run command below to generate migration file. note that you must replace <MigrationName> with your proper Migration Name.
PM> Add-Migration <MigrationName>
and when the migration file created, use the following command to apply migration to database:
PM> Update-Database
Wait for the Done. to appear.

Related

How to retrieve data from SQL Server database into the application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I am creating a web app using Razor pages in ASP.NET Core. How can I retrieve data from my database? I am trying to connect my database with the application.
[Table("Employee")]
public class Employee
{
[Key]
public Guid EmployeeId { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string Address { get; set; }
public byte Status { get; set; }
}
This is how the models look which is auto-created after running the command scaffold-DbContext.
How can I retrieve data from the DB?
You only create your model. You had already created the database, please skip step 6.
To retrieve data from an existing database in EF Core, you should do the following step:
1. Create an App
Create an ASP.NET Core app .NET 6.
Install the following NuGet packages:
Microsoft.EntityFrameworkCore.SqlServer 6
Microsoft.EntityFrameworkCore.Tools 6
2. Create the Models
Create a model for your existing SQL Server database. You can create the model by Scaffold-DbContext command or manually.
To create models from existing SQL Server database use Scaffold-DbContext command:
Scaffold-DbContext "Server=(localdb)\\mssqllocaldb;Database=WebAPI;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
In Visual Studio, the commands is typed in Package Manager Console.
The model could be created manually as follow:
public class Employee
{
[Key]
public Guid EmployeeId { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string Address { get; set; }
public byte Status { get; set; }
}
You have done this step.
3. Create a Context
If you used Scaffold-DbContext command, the dbContext was created automatically. The name of the db context class is [Your Database Name]Context. In this example is WebAPIContext.
You could also create db context class manually as follow:
public class WebAPIContext: DbContext
{
public DbSet<Employee> Employees { get; set; }
}
4. Configure database connection
Add the following code to appsettings.json file
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=WebAPI;Trusted_Connection=True;MultipleActiveResultSets=true"
},
5. Add AddDbContext service
Add the following code to Program.cs file
builder.Services.AddDbContext(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
, optionsLifetime: ServiceLifetime.Scoped);
6. Add-Migration and Update-Database command
Use the Add-Migration init1 command to scaffold a migration to apply these changes to the database.
Run the Update-Database command to apply the new migration to the database.
Remark: If you have not created the database, you should do step 6.
Now you can retrieve data from SQL database and make CRUD operations on your database.
To list employees, replace the following code in the Razor page:
public class IndexModel : PageModel
{
private readonly WebAPIContext _context;
public IndexModel(WebAPIContext context)
{
_context = context;
}
public List<Employee> Employees { get; set; }
public async Task OnGetAsync()
{
Employees = _context.Employees.ToList();
}
}
You have great tutorial in answer above, first of all check key aspects:
have you made connection to Db? (DB Context)
is Db connection string correct (in appsettings.json)
have you registered DbContext in services in Startup.cs to use in Dependency Injection
are you properly using db context in other classes - you can compare with tutorial approach to db context
cheers

Entity Framework Core error "Column names in each table must be unique"

I have manually added the column IdCategory to my table Books, and now each time I try to run Update-Database, I get this error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (43ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [Books] ADD [IdCategory] nvarchar(max) NULL;
Failed executing DbCommand (43ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
Column names in each table must be unique. Column name 'IdCategory' in table 'Books' is specified more than once.
I have found in many forums this type of problem but the solutions don't solve in my case.
How I can solve this problem ?
Here are my models:
public class Book
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public int IdCategory { get; set; }
}
public class BookCategory
{
[Key]
public int IdCategory { get; set; }
[Required]
public string Description { get; set; }
}
Try running add-migration, then delete the code within it and then apply an update-migration. That should sync your model with the database.
I have solved in this way:
Delete the table on DB __EFmigrationHistory
Delete all c# files inside migration folder
Run Add-Migration initial
Review the file inside migration folder ex. 20210105181328_Initial.cs
Delete on "up" method all parts that you don't want create on db becouse already exist or cause issue.
Run Update-Database
This work for me
A general approach to solving this problem is to search within the file created under the Migrations folder for the alleged duplicate column name. Finding both (slightly different) column instances there should quickly tip you off to the cause.
For example, you might find two instances that only differ in their case (e.g., ID vs. Id) and maybe the column type. I've seen it where even if you've been consistent in your casing, EF Core might change the case in order to get around another problem existing in your model.

Can't access database when I change asp.net mvc model properties

I'm developing a project and I made changes to my models, and now whenever I run my project I get these errors for all the model that I made changes to:
for my person model:
Invalid column name 'Location'.
Invalid column name 'EmailAddress'.
Invalid column name 'PlaceOfBirth'.
for my guardian model:
Invalid object name 'Admission.Guardian'.
Here is my DbContext model:
public class SchoolInfoEntities: DbContext
{
public DbSet<Students> Student { get; set; }
public DbSet<Class> Classes { get; set; }
public DbSet<Guardian> Guardians { get; set; }
public DbSet<Staff> Staffs { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<SchoolDetails> SchoolDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Students>()
.HasMany(t => t.Guardians)
.WithMany(t => t.Students)
.Map(m =>
{
m.ToTable("Admission.StudentGuardian");
m.MapLeftKey("StudentId");
m.MapRightKey("GuardianId");
});
modelBuilder.Entity<Staff>()
.HasMany(t => t.Subjects)
.WithMany(t => t.Staffs)
.Map(m =>
{
m.ToTable("Admission.SubjectInstructor");
m.MapLeftKey("StaffId");
m.MapRightKey("SubjectName");
});
modelBuilder.Entity<Staff>()
.HasMany(t => t.Departments)
.WithMany(t => t.Staffs)
.Map(m =>
{
m.ToTable("Admission.StaffDepartment");
m.MapLeftKey("StaffId");
m.MapRightKey("DepartmentId");
});
Database.SetInitializer<SchoolInfoEntities>(null);
}
}
Is there anything that I'm not considering? Please help me guys.
You can't change the model fields without updating the related database fields. You need to create a migration and apply it in order to keep your models in sync with the database schema.
https://docs.asp.net/en/latest/data/ef-mvc/migrations.html
If you have a production version of the database you'll need to run the same migrations on it.
You need to run below commands on the Package Manger console before run your app.
Note : you need to set correct connection string where the place (db server) you need to run the scripts.
PM> Add-Migration "Added_New_Properties"
PM> Update-Database
Since you are using Code First, EntityFramework always make sure that the model is synchronized with the database, when the application starts, it compares the classes and its properties with the tables and columns in the database taking into consideration any changes you made using the Fluent API inside your Context.
When you add a new property into any class, you have to either add a corresponding column in the database table that maps to this class, or you can let EntityFramework do it for you by using Migration.
You have to enbale migration first using the Enable-Migrations command
After that, run the command Add-Migration [Migration Name] which will compare the model to the database and generate some code inside the Migrations folder to update the database, it should have an Up and Down methods.
To run the Up method which updates the database to the code, you have to run the Update-Database command.
All of these commands must run inside the Package Manager Console which you can reach from Tools -> NuGet Package Manager -> Package Manager Console.

ASP NET MVC 3 - How to reset database in code first, with two tables and Database.Setinitializer?

My problem lies in the lack of experience in MVC. Basically, I have two tables in DB
-Person
-Offer
For each I have created a model and a controller and a model, so the structure looks like that:
public class Offer
{
public int OfferID { get; set; }
public string OfferTitle { get; set; }
public string State { get; set; }
public string Description { get; set; }
}
public class OfferDBContext : DbContext
{
public DbSet<Offer> Offers { get; set; }
}
This is the Offer model.
public class Person
{
public int PersonID { get; set; }
public string Username { get; set; }
public DateTime Birthday { get; set; }
public string Education { get; set; }
public string Email { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> Persons { get; set; }
}
This is the Person model.
Firstly I created the Person model, that added itself to db without any problems. Then I wanted to add Offer table, and I had to use the DropCreateDatabaseIfModelChanges method. I used it for OfferInitializer and PersonInitializer and then there is the Global.asax.cs file
protected void Application_Start()
{
Database.SetInitializer<OfferDBContext>(new OfferInitializer());
Database.SetInitializer<PersonDBContext>(new PersonInitializer());
//Database.SetInitializer<PersonDBContext>(new PersonInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
From what I understand, I cant do that simply because I am dropping database 2 times, each time populating only one table at a time. How do I reorganize it all, so that I can populate both or more tables at a time, or the whole database?
First things first, you should not create individual DbContext classes for each table. You should instead put all your DbSets in the same DbContext. Doing this will simplify things greatly for you.
Secondly, you should look into using migrations. You should start using them very early in your project.
You work with code first migrations using the Package Management Console.
enable-migrations
Does exactly what the name implies. Initializes migrations in your project. This will create a folder inside your project and generate the files needed.
add-migration InitialCreate
This creates a migration. InitialCreate is actually a string and you can change it to whatever you want. This command will generate the scripts needed to create the database from strach.
update-database
This command verifies the database and applies the migration (or migrations - there can be multiple) required in order to get the database up-to-date.
This is the initial setup. If you do further changes to your first code first classes, or add more, you will just have to add a new migration and then execute it.
add-migration AddedFirstName
update-database
It's that simple!
There are some more advanced concepts like seed, rollback, update to specific migration, etc., but what I have typed above covers the basics and the day to day usage of migrations.
I recommend you to read this article which explains everything in much more detail: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

Entity framework 6 add-migration adding all tables/entities in Migration Script

I am trying to run the code first migration in entity framework 6.0. I have added 4 new entities in my entities modal. However when i run the "add-migration" command in VS 2013, the generated migration file contains the script of all entitles (just like the initial migration) in my modal, though they are already in linked database. Obviously when I rum "Update-Database" commends, it generates entity already exists error. My DBContext class looks like following:
public class BidstructDbContext : DbContext
{
public BidstructDbContext() : base(nameOrConnectionString: "Bidstruct")
{
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Permission> Permissions { get; set; }
public DbSet<Company> Company { get; set; }
// New Added Table
public DbSet<Gadgets> Gadgets { get; set; }
public DbSet<Language> Language { get; set; }
public DbSet<LanguageKeys> TranslationKeys { get; set; }
public DbSet<Translations> Translations { get; set; }
static BidstructDbContext()
{
Database.SetInitializer(new DatabaseInitializer());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
and DatabaseInitializer class looks like as following:
public class DatabaseInitializer :
// CreateDatabaseIfNotExists<BidstructDbContext> // when model is stable
DropCreateDatabaseIfModelChanges<BidstructDbContext> // when iterating
{
private const int AttendeeCount = 1000;
// EF is NOT a good way to add a lot of new records.
// Never has been really. Not built for that.
// People should (and do) switch to ADO and bulk insert for that kind of thing
// It's really for interactive apps with humans driving data creation, not machines
private const int AttendeesWithFavoritesCount = 4;
protected override void Seed(BidstructDbContext context)
{
}
}
Any idea, how to resolve this problem. Its was working fine for me few days back but now I am facing this problem :(
Check to see if your context keys have changed, in your migration history.
I'm working on a project that has been using automatic migrations, but the automatic migration was not occurring due to a lot of class changes. In trying to switch to non-automatic migration, Add-Migration was regenerating the entire schema.
So I tried putting the manual table changes into the Up() of the DbMigration, and this applied a migration and an entry into the __MigrationHistory table, but with a different context key (the namespace and class name of my configuration file.)
A quick test of renaming the previous (older) migration record's context key to be the same as the current one caused the migration up/down to generate correctly.
Even then...it may not be 100%. Most of my changes were correct, but it started out adding a table which already existed, then turned around and removed it.

Categories

Resources