I made a c#.NET WebAPI and it worked, but when I changed the model it stopped working and it gives me the following error message.
The model backing the 'ApiDbContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database.
This is my code:
The Model (unchanged):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
//public DateTime startTime { get; set; }
//public DateTime endTime { get; set; }
//public int Age { get; set; }
//public string Adress { get; set; }
}
}
The Model (changed):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime startTime { get; set; }
//public DateTime endTime { get; set; }
//public int Age { get; set; }
//public string Adress { get; set; }
}
}
The Controller (changed at updateUser):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Test.DBA;
using Test.Models;
namespace Test.Controllers
{
public class UserAPIController : ApiController
{
ApiDbContext dbContext = null;
public UserAPIController()
{
dbContext = new ApiDbContext();
}
[HttpPost]
public IHttpActionResult InsertUser(User user)
{
dbContext.Users.Add(user);
dbContext.SaveChangesAsync();
return Ok(user.Name);
}
public IEnumerable<User> GetAllUser()
{
var list = dbContext.Users.ToList();
return list;
}
[HttpPost]
public IHttpActionResult DeleteUser(User user)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
return Ok(user.Name);
}
[HttpGet]
public IHttpActionResult ViewUser(int id)
{
var student = dbContext.Users.Find(id);
return Ok(student);
}
[HttpPost]
public IHttpActionResult UpdateUser(User user)
{
User std = dbContext.Users.Find(user.Id);
std.Name = user.Name;
std.startTime = user.startTime;
//std.endTime = user.endTime;
//std.Age = user.Age;
//std.Adress = user.Adress;
dbContext.Entry(std).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChangesAsync();
return Ok();
}
}
}
DBContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Test.Models;
namespace Test.DBA
{
public class ApiDbContext :DbContext
{
public ApiDbContext() : base("Connection")
{
}
public DbSet<User> Users { get; set; }
}
}
Connection string:
<connectionStrings>
<add name ="Connection" connectionString="Data Source=.\SQLExpress;Initial Catalog=k;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Type Enable-Migrations in package-manager-console, after type add-migration, set name, then type update-database
https://msdn.microsoft.com/en-ca/data/jj591621(v=vs.113).aspx
Enable-Migrations: Enables the migration in your project by creating a Configuration class.
Add-Migration: Creates a new migration class as per specified name with the Up() and Down() methods.
Update-Database: Executes the last migration file created by the Add-Migration command and applies changes to the database schema.
more Details:
https://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx
Related
Good morning everyone, I'm learning to use asp.net core in version 6 and I'm having problems saving a record to the database it shows the following error:
SqlException: Invalid object name 'VehiclePerson'.
From what I know, it is actually because it does not find the table in "VehiclePerson" although the connection is made, so I used Scaffolding to obtain the DB from Microsoft SSMS and I created the models and the Context file, so I don't think there are problems with the connection.
This is my VehiclePerson.cs file
using System.Collections.Generic;
namespace APITDCON.Models.QQGUAR01;
public partial class VehiclePerson
{
public string? EmpNumber { get; set; }
public string? Lastname { get; set; }
public string? Firstname { get; set; }
public string? Costcenter { get; set; }
public string? Department { get; set; }
public string? CredentNumber { get; set; }
public string? FromDate { get; set; }
public string? ToDate { get; set; }
public string? Rights { get; set; }
public int Id { get; set; }
}
This is my VehiclePerson.cs file
using Microsoft.EntityFrameworkCore;
using APITDCON.Models.QQGUAR01;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace APITDCON.Data
{
public class APITDCONContext : DbContext
{
public APITDCONContext(DbContextOptions<APITDCONContext> options) : base(options)
{
}
public DbSet<VehiclePerson> VehiclePerson { get; set; }
}
}
This is my VehiclePerson.cs file
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using APITDCON.Models.TANKFARM;
using APITDCON.Models;
using APITDCON.Data;
using System.Collections;
namespace APITDCON.Controllers
{
public class VehiclePersonController1 : Controller
{
private readonly APITDCONContext _apiTDCONContext;
public VehiclePersonController1(APITDCONContext apiTDCONContext)
{
_apiTDCONContext = apiTDCONContext;
}
[HttpGet]
public async Task<IActionResult> Index()
{
List<VehiclePerson> lista = new List<VehiclePerson>();
lista = GetAllDataDrivers();
return View(lista);
}
[HttpGet]
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(VehiclePerson vehiclePersonRequest)
{
string mensaje = "";
var vehicleperson = new VehiclePerson()
{
EmpNumber = vehiclePersonRequest.EmpNumber,
Lastname = vehiclePersonRequest.Lastname,
Firstname = vehiclePersonRequest.Firstname,
Costcenter = vehiclePersonRequest.Costcenter,
Department = vehiclePersonRequest.Department,
CredentNumber = vehiclePersonRequest.CredentNumber,
FromDate = vehiclePersonRequest.FromDate,
ToDate = vehiclePersonRequest.ToDate,
Rights = vehiclePersonRequest.Rights
};
using (var db = new Models.QQGUAR01.Qqguar01Context())
{
var result = new List<VehiclePerson>();
result = (from data in db.VehiclePerson
select new VehiclePerson
{
EmpNumber = data.EmpNumber,
Lastname = data.Lastname,
Firstname = data.Firstname
}).ToList();
}
_apiTDCONContext.VehiclePerson.Add(vehicleperson);
_apiTDCONContext.SaveChanges();
return RedirectToAction("Add");
}
}
}
Database and table
Error
The table name defined in your database context is VehiclePerson, but your table name in the database is VEHICLE_PERSON, the two names do not match.
The easiest way is to change the name of the table VEHICLE_PERSON in the database to VehiclePerson, or change public DbSet<VehiclePerson> VehiclePerson { get; set; } to public DbSet<VehiclePerson> VEHICLE_PERSON { get; set; } in your context.
If you want to avoid similar situations in the future, you can use the following commands to migrate and update the database after adding Scaffolding:
Add-Migration InitialCreate
Update-Database
For more details on scaffolding and connecting to the database, you can refer to this official document.
By default EF will use entity name as table name so you can override it in multiple ways, for example using Table attribute:
[Table("VEHICLE_PERSON")]
public partial class VehiclePerson
{
}
i want to add a new user into my database but i get this error System.InvalidOperationException: 'The entity type User is not part of the model for the current context.'
UserController.cs Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Registration.Models;
namespace Registration.Controllers
{
public class UserController : Controller
{
[HttpGet]
public ActionResult AddOrEdit(int id=0)
{
User userModel = new User();
return View(userModel);
}
[HttpPost]
public ActionResult AddOrEdit(User userModel)
{
using (DBModels db = new DBModels())
{
db.Users.Add(userModel);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.SuccessMessage = "Registration Successful.";
return View("AddOrEdit", new User());
}
}
}
User.cs Class inside folder Models
namespace Registration.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class User
{
public int UserID { get; set; }
[Required(ErrorMessage = "This field is required.")]
public string Username { get; set; }
[Required(ErrorMessage = "This field is required.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[DisplayName("Confirm Password")]
[Compare("Password")]
public string ConfirmPassword { get; set; }
public bool IsAdmin { get; set; }
}
}
So I'm here following a tutorial step by step and can't get rid of this exception. My connection string looks fine. It doesn't happen in the tutorial so I have no idea what is wrong.
It brings me to this line Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ATSTest.Models;
namespace ATSTest.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Details(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
return View(employee);
}
}
}
Here is my Class
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace ATSTest.Models
{
[Table("Employees")]
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string HiredDate { get; set; }
}
}
Connection String
<connectionStrings>
<add name ="EmployeeContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=AssetTracking;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
EmployeeContext Class
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ATSTest.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
The answer to your question is you are not using the connection string.
You will have to pass connection string name as shown in below example.
public class EmployeeContext : DbContext
{
public EmployeeContext()
: base("EmployeeContext")
{
}
// DbSet's here
publlic DbSet<Employee> Employees { get; set; }
}
I start studying asp.net MVC and I am confused about sending data to VIEW. I have one class Dispatch:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Logistic.Models
{
public class Dispatch
{
public int DispatchId { get; set; }
public int TrackingId { get; set; }
public int CustomerId { get; set; }
public int RecipientId { get; set; }
public int CityId { get; set; }
public DateTime Delivered { get; set; }
public string Notes { get; set; }
}
}
Another class City:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Logistic.Models
{
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
}
}
A class Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Logistic.Models
{
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
}
}
From my class Dispatch, CustomerId and RecipientId will be related to the class Client; CityId related to City.
I create my context class:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace Logistic.Models
{
public class LogisticContext : DbContext
{
public DbSet<Dispatch> Dispatches { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Driver> Drivers { get; set; }
public DbSet<City> Cities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
And here is my Controller:
using Logistic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Logistic.Controllers
{
public class HomeController : Controller
{
private LogisticContext db = new LogisticContext();
public ActionResult Dispatch()
{
var dispatches = db.Dispatches.ToList();
return View(dispatches);
}
}
}
The problem is that in my View class I do not know how to display the Customer Name, Recipient Name, and City Name. I only can display the CustomerId, RecipientId, and CityId.
View:
#model IEnumerable<Logistic.Models.Dispatch>
#{
ViewBag.Title = "Dispatch";
}
<h2>Dispatch</h2>
#foreach(var item in Model)
{
<h2></h2>
}
Thanks
If you have relationships in place...
If you already have defined relationships between these properties, you can generally use the Include() method to pull related entities in as seen below :
// Pull all of the dispatches and their related cities
var dispatchesWithCities = db.Dispatches.Include("Cities")
.ToList();
If you do this and have the proper relationships, you would then be able to iterate through and access the item.City.Name, however it doesn't look like that is the case in your current scenario.
Without relationships...
If you don't have these "hard" relationships in place, you can still perform a few database queries to pull the properties you need and construct a ViewModel, but it wouldn't be pretty with so many results :
public class DispatchViewModel
{
public Dispatch Dispatch { get; set; }
public City City { get; set; }
public Client Client { get; set; }
public Driver Driver { get; set; }
}
And then use each of your individual Dispatch objects and map them to their related properties :
// Build your Dispatches with related information
var dispatchModels = db.Dispatches.AsEnumerable()
.Select(d => new DispatchViewModel()
{
Dispatch = d,
City = db.Cities.FirstOrDefault(c => c.CityId == d.CityId),
Client = db.Clients.FirstOrDefault(c => c.ClientId == d.CustomerId),
...
});
At this point you can simply iterate through the collection and output them by referencing the iterator in the loop :
#foreach(var item in Model)
{
<h2>#item.Dispatch.DispatchId</h2>
<ul>
<li>
<b>City</b>: #item.City.Name
<!-- Other stuff here -->
</li>
</ul>
}
You can use view model approach to send data from mutliple views to controller. Here is an example:
http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp-net-mvc-applications/
I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I want to customize my interface depending on the type of user logged.
I was following
this tuto
in the microsoft site and i am stuck when he use ActionLog instance in the filter class (ActionLogFilterAttribute).
Infact, this class is declared in 'StoreDB.designer.cs' class which i don't have because i created my project using the 'code first' method of Entity Framework.
I have only this class for the context :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication2.Models
{
public class GammeContext : DbContext
{
public GammeContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<GammeContext>());
}
public DbSet<Account> Accounts { get; set; }
public DbSet<Ns_AFaire> Ns_AFaires { get; set; }
public DbSet<Famille> Familles { get; set; }
public DbSet<Fonction> Fonctions { get; set; }
public DbSet<Fonction_Poste> Fonction_Postes { get; set; }
public DbSet<Gamme> Gammes { get; set; }
public DbSet<Historique> Historiques { get; set; }
public DbSet<Ligne> Lignes { get; set; }
public DbSet<Phase> Phases { get; set; }
public DbSet<Poste> Postes { get; set; }
public DbSet<Produit> Produits { get; set; }
public DbSet<Profile_Ga> Profil_Gas { get; set; }
public DbSet<Sous_Famille> Sous_Familles { get; set; }
public DbSet<UF> UFs { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Num_Serie> Num_Series { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
}
and this is the filter class that i created :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Filters
{
public class ActionLogFilterAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
GammeContext db = new GammeContext();
ActionLog log = new ActionLog()
{
Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
Action = filterContext.ActionDescriptor.ActionName,
IP = filterContext.HttpContext.Request.UserHostAddress,
DateTime = filterContext.HttpContext.Timestamp
};
db.AddToActionLogs(log);
db.SaveChanges();
base.OnActionExecuting(filterContext);
}
}
}
So, is there any solution ??
The ActionLog instance he is using is the Enitity that is related to his ActionLog table.
What you need to do is to add your own ActionLog entity - that is all :)