Table not mapped using EF code first approach - c#

I'd like to use EF code first approach. I added the database and I generate the tables . Then I added this class
public class Invitation
{
[Key]
public int Id { get; set; }
[DefaultValue(false)]
public bool State { get; set; }
public string Mail { get; set; }
public string Tel { get; set; }
public string Name { get; set; }
public string Qr_code { get; set; }
}
I run these command then :
add-migrations second
update-database
the Up and Down methods of the second class migration are empty!! and no table is added to the database.
The context
public class ApplicationContext: IdentityDbContext<ApplicationUser>
{
public ApplicationContext()
:base("DefaultConnection")
{
Database.SetInitializer<ApplicationContext>(new CreateDatabaseIfNotExists<ApplicationContext>());
}
public static ApplicationContext Create()
{
return new ApplicationContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
So I need to know
What is the reason of this problem?
How can I fix it?

Looks like you forgot to tell Entity Framework about the new table that you want added (DbSet<Invitation>)
Once you add this, Entity Framework should add the table(s) you want added in the Migration script, respectively.
In summation, you would need to add this line :
public DbSet<Invitation> Invitations { get; set; }
and/or
public IDbSet<Invitation> Invitations { get; set; }
and run another Migration Script.

Try adding the following into your ApplicationContext class
public DbSet<Invitation> Invitations { get; set; }
Then running;
Enable-Migration
Add-Migration note_of_changes
Update-Database

I think you need to create an initial migration. If this is your first migration (note that this will clear your existing migration history so only use if you're happy to discard your existing migration history)
Delete your Migrations folder in the solution
Remove your changes (remove the reference to the new table from your DbContext). Note that -IgnoreChanges could well make this step redundant but I can't say for certain.
Remove the MigrationHistory table from your database (it most likely won't exist but you can go ahead and delete it if it is)
Now enable migrations (in package manager console)
Enable-Migrations
Then create your initial migration. This will create a migration matching your existing schema with empty methods
Add-Migration Initial –IgnoreChanges
Update-Database
Then update your DbContext with your new table reference and make any other changes you need to and do
Add-Migration MyChanges
Update-Database
That should apply the changes to the database. Some more info over at MSDN if you need it.

Related

Consuming View in EF Code First conflicts with migration

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.
According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.

Entity Framework invalid object name "dbo.EA_EmployeePerformance"

It is weird since I use the simple membership initialization my EF model cannot create a new table. My code was able to create the new table needed if there is a transaction required for the model.
This is my model :
public class EmployeeDBContext : DbContext
{
public EmployeeDBContext()
: base("DefaultConnection")
{
Database.SetInitializer<EmployeeDBContext>(new CreateDatabaseIfNotExists<EmployeeDBContext>());
}
public DbSet<EA_Employee> Employees { get; set; }
public DbSet<EA_EmployeePerformance> EmployeePerformances { get; set; }
public DbSet<EA_EmployeeRank> EmployeeRanks { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
[Table("EA_EmployeePerformance")]
public class EA_EmployeePerformance
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Display(Name = "Employee Performance Id")]
public int EmployeePerformanceId { get; set; }
[Index("Performance", IsUnique = true)]
[MaxLength(20)]
[Required]
public string Performance { get; set; }
public EA_EmployeePerformance()
{
Performance = "";
}
}
Whenever I SaveChanges(), the DB throws me
"Invalid object name dbo.EmployeePerformance".
I check the database and the database only contains tables required from simple membership.
How can I auto create the tables when a transaction is occurred for that model?
--------- EDITED ---------
Now I know what is my problem. The problem is because I use multiple dbContext in one database. It is gonna be tricky to do the migration because migration only works on one dbContext isn't it?
So in my case the problem is because the original AccountDBContext from the simple membership is taking over my database, that is why my other dbContext such as the EmployeeDBContext cannot create the new table (please correct me if i'm wrong).
Is there a way for me to keep the multiple dbContexts in a single database?
First you have to change your Db Initializer to DropCreateDatabaseIfModelChanges otherwise, you will still have the old database and you will never get the model changes without deleting the database manually.
database. It is gonna be tricky to do the migration because migration only works on one dbContext isn't it?
For migration I recommend you to create one DbContext for migration that called for Example MigrationDbContext which contains the the all DbSets and the POCO objects, also when the POCO objects belong to other assembly then just reference them.
Try using Migrations, this will help you manage your changes in your code and update the database scheme accordingly.
Here is a guide for how to use it Migrations.

Entity Framework 7 Update DbContext after migration

I've got an existing DB and new WPF project.
1) I scaffolded db context with Scaffold-DbContext and recieved DbContext.cs and a file for each entity that represents a DB tables. That's OK.
Here is example of one of them:
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
}
2) I've manually updated this entity (no changes in DbContext.cs) :
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
3) I've used Add-Migration command. Now I've got a migration file that describes required changes and DbContextSnapshot.cs. Snapshot includes changes I've just made with SomeEntity. Database is not updated.
4) I've used Update-Database command. Database updated to match last migration. But my DbContext.cs doesn't know anything about changes in DB. It is still the same old good DbContext that I had after scaffolding DB.
Is this OK? Should I now change DbContext manually to match changes that I've made to my entities and applied them to DB? Is there a way to update DbContext.cs from DB after changes without 'rescaffolding'? (Because, for example, all comments and attributes in entity files will be lost, because they will be replaced with new ones if I use Scaffold-DbContext again)
You will have to run scaffolding again, but keep in mind that the generated classes are partial, so you can put your changes in another file

edit user profile image with usermanager

I'm following this tutorial to add profile picture once account create.
that edit has following snippet,
Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id);
In above example it applied to table call Student in my case I want to go with AspNetUser table , but then I have to go with UserManger feature , Once I try to Include a file then it popping that error in compile time.
But in my scenario I'm trying to include in AspNetUser or UserManager
So to populate uploaded picture. I need include following code in user manager
var user = await UserManager.Include(s => s.Files).FindByIdAsync(userid);
but then getting following error
'ApplicationUserManager' does not contain a definition for 'Include'
and no extension method 'Include' accepting a first argument of type
'ApplicationUserManager'
How to ignore and include files
EDIT:
These are the changes I've done in Model classes
File
public class File
{
public int FileId { get; set; }
..
public virtual ApplicationUser UserManager { get; set; }
}
FilePath
public class FilePath
{
public int FilePathId { get; set; }
..
public virtual ApplicationUser UserManager { get; set; }
}
ApplicationUser
public class ApplicationUser : IdentityUser
{
....
public virtual ICollection<File> Files { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
....
}
}
AspNetUser
public partial class AspNetUser
{
public AspNetUser()
{
..
}
....
public virtual ICollection<File> Files { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
}
then try to add migration to the project by typing the following into the PMC:
add-migration File
add-migration FilePaths
then getting following error in console
No migrations configuration type was found in the assembly
'Project_Name'. (In Visual Studio you can use the Enable-Migrations
command from Package Manager Console to add a migrations
configuration).
then I typed the following into the PMC:
Enable-Migrations project_name.Models.sampleEntityFrameworkEntities
then I got following error in console
Creating a DbModelBuilder or writing the EDMX from a DbContext created
using Database First or Model First is not supported. EDMX can only be
obtained from a Code First DbContext created without using an existing
DbCompiledModel.
then I try to migrate Files and FilesPath using following code
add-migration File
add-migration FilePaths
Get error in console
Creating a DbModelBuilder or writing the EDMX from a DbContext created
using Database First or Model First is not supported. EDMX can only be
obtained from a Code First DbContext created without using an existing
DbCompiledModel.
If I understood you correctly you're trying to follow the guide but using ASP.NET Identity. ASP.NET Identity is a unique system with its own classes and DBContext. In order to add new fields to the user you need to modify ApplicationUser class. Just add your property to this class and apply migration if needed. This will add a new column to the AspNetUser. Then add your field to the ViewModel (if any) and to other logic that is required to work with your field.

Add Table To Database In MVC and Web Api Project

I have made a project in which i have choose MVC + Web Api template with Authorized attribute.I have made my SQL Data base on Windows Azure and publish my project successfully.I can see the data of the registered user in users table.
Now i wanted to add one more table to my Database but i am not getting how to do it.I know i have to make a model of that table type and update the database.But i don't getting how to write this part in code.I am total newbie in this part.
I have seen Account controller class it is looking just an alien to me :)
can somebody help me.
Step 1: Create the model for your table
public class Comment
{
public int ID { get; set; }
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public virtual ApplicationUser Author { get; set; }
}
Step2: Add a dbSet for this model in your DbContext class
public class DDBContext : DbContext
{
public DDBContext()
{
/* ... */
}
// add the DbSet
public DbSet<Comment> Comments { get; set; }
//... additional models ommitted
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DDBContext, Configuration>());
}
}
Step 3: Enable Migrations
In the packagemanager console issue those commands:
enable-migrations
add-migration MyNewTableAdded
Step 4: Build the project
Step 5: Issue the update-database command in the packagemanager console
There is a detailed explanation on www.asp.net including the process for Azure. Click here!

Categories