Insert and Read from Table ASP.NET MVC 5 - c#

I've been banging my head all day long. I'm new to MVC 5 (MVC and ASP.NET in general) and I can't figure out how do I add an extra table to my current Database (created using CodeFirst approach), and read its content.
Heck, I don't know how to read the other columns I have in the AspNetUsers Table from Identity.
Would someone kindly tell me how this is done? Thanks a million
Edit:
Ok. So I have been tirelessly looking for a solution, and I've come across 35% of it.
I've stumbled upon a book called "Getting Started with Entity Framework 6 Code First using MVC 5 with Tom Dykstra"
Now I know that for creating a table you just create a class under the Model folders, and use a DbSet<> command where you had applied the DbContext call.
Now, what's the problem here? I started from a blank template, since that is the suggestion from "Pro ASP.NET MVC 5" from Adamn Freeman, and I don't want Google, Facebook Authentication.
I have been able to populate the defacto AspNetUsers table with custom fields, and insert Data into it.
What I want to with it, is to create a relational table with a foreign key which should reside in the defacto AspNetUsers table, and I don't how to do it.

Create the entity class (new table). You must specify an attribute as the primary key that should be named (CLASSNAME)ID Ex:
public class Product
{
public int ProductID { get; set; }
public string PropriedadeTeste { get; set; }
}
Map this entity in your implementation of DbContext. This means that Products table will contain Product objects:
public class EFDbContext : DbContext
{
public EFDbContext() : base("DatabaseName") { }
public DbSet<Product> Products { get; set; }
}
Enable migrations in your project (in the Package Manager Console)
Enable-Migrations -ProjectName SportStore.Domain -ContextTypeName ENTER_NAMESPACE_HERE.EFDbContext
Generate the migration - in this example, it will be generated a file named something like 201409172255007_Product.cs, in the Migrations folder:
Add-Migration -ProjectName PROJECT_NAME Product
Update the database:
Update-Database -ProjectName PROJECT_NAME -TargetMigration Product

Related

EF not updating temporal table from code first [duplicate]

I have an EF Core 6 context that uses temporal tables, and am trying to rename one of the properties on a model.
I have a model that was named PropertyGroupsInvestors, which I renamed to Investment. That worked fine.
I then noticed that the InvestorPayment model had the following...
public int PropertyGroupsInvestorsID { get; set; }
public PropertyGroupsInvestors PropertyGroupsInvestors { get; set; } = new();
...which should also have been renamed. I renamed the two properties as follows...
public int InvestmentsID { get; set; }
public Investment Investment { get; set; } = new();
...and added a migration.
However, when I tried to update the database, it failed with the error "Setting SYSTEM_VERSIONING to ON failed because table 'MyProject.dbo.InvestorPayments' has 10 columns and table 'MyProject.dbo.InvestorPaymentsHistory' has 9 columns."
Looking in SQL Server Management Studio, I can see that both the InvestorPayments and corresponding history tables have both the old PropertyGroupsInvestorsID column and the new InvestmentId column. They both have 10 columns, so I'm not sure what he message means though. See the screenshot...
Any idea how I fix this? Ideally I need to get rid of the PropertyGroupsInvestorsID column from both tables.
Thanks
There is a problem with the renaming of columns in the system versioning table using a code-first approach. So a quick solution (if you don't want to drop temporal tables) can be just to create two migrations. One migration to add a new column, and the second migration to remove the old column.
So first migration will contain both, PropertyGroupsInvestorsID and InvestorsID and then remove PropertyGroupsInvestorsID to create a new migration.
The same problem here like deleting or modifying one field, it looks like when you have a system-versioned table, you can't modify the structure because it's linked to the history table.
Using SQL server doesn't look like there is any problem:
https://learn.microsoft.com/en-us/sql/relational-databases/tables/add-columns-to-a-table-database-engine?view=sql-server-ver15

How can I update the database model after doing a migration in .NET Core 3.1 using Entity Framework?

I'm new, excuse my ignorance.
I have this class:
public class Genre
{
public int Id { get; set; }
[Required]
[StringLength(40)]
[Index(IsUnique = true)] //-----------------------> new change
public string Name{ get; set; }
}
In my first migration called Initial, I forgot the [Index(IsUnique = true)] attribute which makes the Name field unique. So now I want to update my database model for this change to take effect.
I installed the package using System.ComponentModel.DataAnnotations.Schema; to be able to use the unique property.
The commands I ran were:
EntityFrameworkCore\Add-Migration Initial
EntityFrameworkCore\update-database
Apparently I can't do something like:
EntityFrameworkCore\Add-Migration change_attribute_name
EntityFrameworkCore\update-database
to update the database model and that I updated the unique attribute on the Name field which is what I am doing.
I would like to update the model of my database, with the new changes. How can I do it? and what is the best way?
Note: my SQL Server database has no data yet.
Maybe I've been doing fine, you know why the unique attribute is not added in my database model?
(In Spanish Genero=Genre and Nombre=Name)
EDIT
In EF core, you need to apply the unique index in the following way using Fluent API in your ApplicationDbContext.cs file:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Genre>()
.HasIndex(u => u.Name)
.IsUnique();
}
Since as you mentioned, you do not have any data in the database yet, you can revert all your applied migration by using
Update-Database -Migration 0
the -Migration 0 indicates that you want to un-apply all the migrations.
Then you can remove your generated migration using
Remove-Migration
And finally, add migration again using new changes by
Add-Migration Initial
Change the model an try adding migration
Add migration yourmigration name
And then run
Update database
Command this will work for you for sure

EF Core Power Tools Reverse engineer create different attributes on model on different SQL servers

I'm using EF Core Power Tools to generate my model by choosing EF Core Power Tools -> Reverse Enegineer within Visual Studio .Net.
I'm still using EF Core 2.x, so I remove the checkmark from the first dialog where you can choose to use EF Core 3.x.
In the last options dialog I select:
Use DataAnnotation attributes to configure the model.
Customize code using Handlebars templates (C#).
I'm using SQL Server for my databases.
My problem is that the model generated is different when I run the tools on my local database compared to a version of the database on another server.
The difference is in the generated POCO class.
On my local database, the following class is generated:
public partial class ExampleTable
{
[Key]
public byte Id { get; set; }
public string Tekst { get; set; }
}
When I run the tool against another database the code looks like this:
[Table("ExampleTable", Schema = "dbo")]
public partial class ExampleTable
{
[Key]
public byte Id { get; set; }
public string Tekst { get; set; }
}
Why is the tool generating the model with attributes on dbo tables on one databse and without attributes on another database?
As #Karan said, this is because the user used for scaffolding does not have dbo as default schema.
see https://github.com/dotnet/efcore/blob/master/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.cs#L174

EF6 Code First Migration with single database multiple context

I'm building an Asp.net MVC5 + EF6 solution with 3 projects.
I have enabled automatic migration in my project.
The below diagram shows my project structure.
I have a main project and two sub projects.
I have a BaseContext in a main project.
Sub project has their own context classes which derives from
BaseContext.
All above contexts are connecting to one database.
Models:
A Model in Project2
public class Product
{
[Key]
public int ProductId {get;set;}
...
}
A Model in Project3
public class Order
{
[Key]
public int OrderId {get;set;}
[ForeignKey("Product")]
public int ProductId {get;set}
public virtual Product Product;
...
}
An property from Project3 entity (Order.ProductId) references a property from Project2 entity (Product.ProductId) as a foreign key reference.
When I run update-databasecommand in project 1 & 2 everything is going well.
But when run update-database command in project 3 It gives an error:
There is already an object named 'Product' in the database.
Right now I'm using update-database -script command to generate script and manually altering the script. But when project grows, it becomes a difficult task to alter sql scripts each and every time.
I ignored the Product entity by adding modelBuilder.Ignore<Product>() inorder to skip table creation for Productentity, in Project3, but it's ignores the entire relationship.
How can I solve this issue?
You can't do this. One context == one database. When you run a migration against a database for a particular context, it will be based on that context, and will remove any non-applicable tables or try to drop and recreate the database.
You should move all your entities into a class library, along with a single instance of a context that includes them all. Then, you can migrate against the class library and simply reference in your other projects.
Alternatively, you can sort of do what you want by going with an existing database approach. Essentially, you turn off migrations entirely on your base context, and then each sub context can then only include the entities that belong to it. However, you're going to be completely responsible for managing the database, yourself, at that point.
public class BaseContext : DbContext
{
public BaseContext()
: base("ConnectionString")
{
Database.SetInitializer<BaseContext>(null);
}
}

Merge MyDbContext to Asp.net IdentityDbContext

I saw a lot of examples online but none that I could use from top to bottom about merging my own DbContext with Asp.net IdentityDbContext.
Can someone please walk me through it? I am at step 0, and what I want is to have the tables generated by ASP.net IdentityDbContext inside my own database, so that I can retain user data in my own database. How can I achieve that?
Thanx in advance :)
If I got you correct, you are trying to use your existing database, tables and existing users with asp.net identity framework.
First thing, according to my understanding, you can't merge your db context (MyDbContext) with 'IdentityDbContext', because context of asp.net identity framework tables has to be inherited from IdentityDbContext<YourUserTable>. But your other tables may inherited from DbContext.
Therefore you have to use two separate db contexts if you want to use identity framework build in method support, which is UserManager etc.
You can use your existing database with identity framework, you just need to correctly bind your database tables with identity framework EF code first approach using model binding.
There is a YouTube video tutorial which may help you to get some idea in order to achieve your task. Actually this video illustrates to use Identity 2.0 with existing database.
Part 1: https://www.youtube.com/watch?v=elfqejow5hM
Part 2: https://www.youtube.com/watch?v=JbSqi3Amatw
Hope this helps.
I'm not really sure what you're trying to achieve but check this question to see if it's of any help.
ASP.NET Identity DbContext confusion
Here's part of a walk-through I created. There are a few steps included specific to making it work with code first migrations but you should be able to accomplish what you want using these steps.
Start by creating a new ASP.NET MVC project. Call it Contacts if you want the included code to match. The authentication defaults to Individual User Accounts which is what we want in this case. Deselect Host in the Cloud for now. You can enter your publishing settings later. Once the project is created bring up the Package Manager Console and Install-Package EntityFramework. Now since we are doing Code First add a simple model class.
public class Contact {
public int ContactID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
At this point you would usually add controllers and such but since this post is focusing on the data side of things we'll skip over all of that. Next we want to add our database context. Go ahead and add it right in the Models namespace.
public class ContactContext : IdentityDbContext {
public ContactContext()
: base("ContactContext") {
}
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public static ContactContext Create() {
return new ContactContext();
}
}
A couple of things to note here. Since we're consolidating the Identity tables into our application's context we want to inherit from IdentityDbContext instead of just DbContext. Also, I prefer not to use the generated "DefaultConnection" that gets created in Web.config so I'm passing "ContactContext" as the connection string name to the base constructor. We'll modify the connection string in a minute. If you're typing in the OnModelCreating method Visual Studio should add the call to base.OnModelCreating but if not make sure you add it since it's essential for building the identity tables. Although not essential, you can configure the modelBuilder not to pluralize table names. Add a Create method which is needed for the Identity code to use this context. Also, as you add code you'll need to right-click and Resolve to add the appropriate using statements.
As promised, here is the modified connection string to be updated in the web.config in the root of the site. The name property is changed to something that makes sense for the application and the AttachDbFilename and Initial Catalog values are changed to something a little more user friendly than the auto generated name.
<add name="ContactContext" connectionString="Data Source=
(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\ContactContext.mdf;Initial
Catalog=ContactContext;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now go to the Models folder and open the IdentityModels.cs file. Cut the ApplicationUser class from here and paste it into your Contact.cs file. Again you'll have to resolve a few missing namespaces. At this point you can safely delete the IdentityModels.cs file. Since we've eliminated the ApplicationDbContext we'll need to do a find on ApplicationDbContext and replace it with ContactContext in a few places. You should be able to do a clean build.

Categories

Resources