Why can't I create a new table in my existing database using EF Core? (Code First) - entity-framework-core

I want to know why I cant add a new table into my existing database.
I've created a new model:
public class RegisterAccount
{
public string Username { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
Added the necessary Dbset
public DbSet<RegisterAccount> RegisterAccount {get; set;}
I've typed in the PMC:
Add-Migration, then Update-Database but I can't see the new table in the database?
I've restarted SSMS and refreshed everything, am i missing something?

Related

How do I stop EF Core from Auto creating Property even though manually configured?

I have the following classes and configuration
public class ApplicationRole
{
public string Id { get; set; }
public List<ApplicationPermission> Permissions { get; set; }
}
public class ApplicationPermission
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string RoleId { get; set; }
}
//Configuration for ApplicationPermission
builder.HasOne<ApplicationRole>()
.WithMany()
.HasForeignKey(r=>r.RoleId);
After running the migrations in my ApplicationPermission table I get 2 filelds RoleId as expected, but also ApplicationRoleId which is automatically created by EF.
So how do I just keep my RoleId in the table and disable EF from creating the other field.
I read that you might need to disable EF conventions. Is that correct and the only way?

Why it is trying to insert NULL in primary key property id.. MVC5 EF6

I am using Entity Framework 6 Code First MVC5.Here is my class:
Offer.cs
public class Offer
{
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
Here is my controller
[HttpPost]
public ActionResult Create(OfferFormViewModel viewModel)
{
var offer = new Offer
{
ListOffer = viewModel.ListOffer,
};
_context.Offers.Add(offer);
_context.SaveChanges();
return RedirectToAction("MyOffers", "Offers");
}
OfferFormViewModel.cs
public class OfferFormViewModel {
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
When I try to insert a record in offers table, it works fine on my machine and inserts record in the database and it automatically assigns value to id column. But when I deploy the application it throws the exception
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'DefaultConnection.dbo.Offers'; column does
not allow nulls. INSERT fails. The statement has been terminated.
My question is why is it trying to insert NULL in Id column when I deploy the application and not when I run the code without deployment?
When I deployed the application I copied the database to the server. On the server the Id column was not set to primary key and it was not an identity column either. I think something went wrong while copying the database to the server. That's why it was throwing the exception.
Use this Model and also update database with migration u can do this by following steps:
Open Tools > NuGet Package Manager > Package Manager Console.
enterenable-migrations in the Package Manager Console
enteradd-migration {name}(make sure your application can built without any error).
enterupdate-database.
public class Offer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
You should use auto-increment, using Data Annotation:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
or FluentAPI
modelBuilder.Entity<Offers>()
.Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Code First doing strange migration when I add an interface to my entities

I have a strange problem with code first:
In project my entities looks like that and code first was doing migrations fine.
public class MyEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
}
I decided to add an interface to my project like this one
public interface IEntity
{
Guid Id { get; set; }
bool IsDeleted { get; set; }
}
My new class now looks like that:
public class MyEntity : IEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
bool IsDeleted { get; set; }
}
Now, if I try a migration with Code First, instead of adding a column here is what is doing code first:
DropForeignKey
DropIndex
Tries to CreateTable MyEntity table and breaks telling me this table already exists
Any idea why code first tries to do that?
Using EF5 I couldn't get it to repro. In general with migrations the order in which commands are executed is important so as the metadata is consistent between the database and models.
The correct order for these operations would be to either:
a) Run Enable-Migrations, Add-Migration then Update-Database before populating the database (i.e. running the app) then Add-Migration and Update database after each model change before running the app
b) run the app, Enable-Migrations, change the model, Add-Migrations, Update-Database, again making sure to run update the database after each model change is made
also note I am using a very simple DbContext that looks as such:
public class EntityContext : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
}

Invalid Column Name with EF

I modified the table UserProfile in the database with some extra columns and then modified the UserProfile class to reflect them:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public string School { get; set; }
}
Obviously they are FirstName, Surname and School. For some reason though despite the register action saving details into all 3 of these new columns when I try to load the data via:
var context = new UsersContext();
var user = context.UserProfiles.First(n => n.UserName == model.UserName);
It says that School is an invalid ColumnName. I checked it was a string in both class and table so bit confused how to debug, help!
(Continued from comments on OP)
Rather than doing this manually, you should consider using the EF migrations framework - There are a number of benefits and it's more future-proof in case internal EF functionality changes.
See here for more information on migrations

Entity Framework Code First Migration manually removed column causing issue with migration

I have a Blog object that has an Admin object. I initially had this setup wrong and it created my columns incorrectly. I manually removed the "Admin_Id" foreign key field and relationship. Now when I run the migration again, it doesn't add the foreign key and relationship back.
Can I force the entity framework somehow to update the database again?
My objects:
Admin
public class Admin: WebPage, IWebPage
{
public string Name { get; set; }
public string Email { get; set; }
public string About { get; set; }
public string Image { get; set; }
public List<Blog> Blogs { get; set; }
}
Blog
public class Blog : WebPage, IWebPage
{
public string Title { get; set; }
public string Summary { get; set; }
public string ArticleBody { get; set; }
public string Author { get; set; }
public DateTime PostingDate { get; set; }
public virtual Admin Admin { get; set; }
public virtual BlogCategory BlogCategory { get; set; }
public virtual List<Comment> Comments { get; set; }
}
The Entity Framework stores the migrations that have been applied to the database in the __MigrationHistory table. If you delete the row in this table representing a particular migration (the MigrationId column contains the name of the migration class), that migration will be reapplied the next time you do an update-database.
That said, this will cause the entire migration to be reapplied, not just the parts of it that happen to be missing in the database, including all table creations, drops, etc., etc., so use it with care if you haven't previously manually backed out the changes that that migration has put in place, as some of those operations can and will cause errors if the database objects already exist.