asp net mvc adding a new property to model - asp.net

I'm new in asp.net mvc. I'm trying to learn entity framework after the database has been created by the first code starting, i m adding a new porperty to model, but controller and view are not updating themselves automatically.
public class test
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname{ get; set; }
}
in this simple I add Surname property after database created. I update database, but view and controller side do not update themselves automatically.
So should I make all changes manually like changing controller "create edit delete" post action.
thanks for answer

You most likely used scaffolding to create them first. If you want to have the properties listed in the view you need to recreate the scaffolding so it knows that property exists. To do that right click on the controller folder add new scaffolded item, like you did before.

You need to update the binding white list so your new property will be included, For this use Ctrl+Shift+B [For Visual Stdio]
after that do the Migration and update the database.

Related

Web API Add controller with CRUD operations for existing Azure table in Existing Azure db

My app performs Authentication with Asp.NET Identity.
The users logging in are stored in dbo.ASPNetUsers
A while ago, I used migrations to add another table called "Customer", but now the table is populated.
How can I add a controller to perform CRUD operations ONLY on existing "Customer"(the other tables have controllers) without dropping the table and risking erasing any of its content or any other content in the existing tables in the db.
What I tried so far:
Create class in Models folder called "Customer" to resemble the table columns
public class Customer
{
[Key]
public string ID {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}
Add DbSetCustomers
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
// : base("DefaultConnection", throwIfV1Schema: false)
: base("MS_TableConnectionString", throwIfV1Schema: false)
{
}
public DbSet<Customer> Customers { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Add new Controller of type Web API 2 Controller with actions using Entity Framework using model class Customer, with data context class as the default ApplicationDBContext (default option when creating controller, im assuming it uses my app connection string for the azure table).
When using the GET customers in POST, I get an error saying the database has changed since last migration, I Imagine this is because adding the DbSet Customers but I do not want to update migration because in the migration code, there is Drop Table command.
Is this right method?
Should I just change the migration script not to drop the table?
Please advise.
"Database has changed since last migration" , it s a way of EF telling that your migration history doesn't match with the tables.
EF's default database generation workflow creates a full script that will recreate your database every time you select Generate Database from Model, so if you execute it in your DB you will lose all your data. However, if you just create a new Entity and did not change the existing ones, then you can still generate database from your Model but then take that script and only run the part that creates the new table for your new entity.
You can take a look at the below link for further reference:
https://www.apress.com/gp/blog/all-blog-posts/secular-trends-for-the-cloud/12097630
https://social.msdn.microsoft.com/Forums/en-US/ed3ccb7e-5e89-4fd4-ae92-d641a5c5bd9a/entity-framework-model-first-make-changes-to-the-database-without-dropping-tables?forum=adodotnetentityframework
https://www.pauric.blog/Database-Updates-and-Migrations-with-Entity-Framework/
Hope it helps.

How to update / generate database table model?

I'm learning ASP.NET Core and I'm having some problems with the following scenario:
I created an extension class for IdentityUser provided by Microsoft.AspNetCore.Identity, the extension class add some extra field to the default database AspNetUsers:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string LockoutMessage { get; set; }
public string SessionId { get; set; }
}
I was able to update the table structure executing the following commands:
add-migration <migration name> -context <app context>
update-database
Problem
Suppose now I used the software Microsoft SQL Server Management Studio for create another table called UserDetails which have as FK the id of the AspNetUsers table.
I want generate the class inside the Models folder with all the properties from my application, so I don't need to write manually the property of the table of the new table, how can I do that?
I tried: update-database but not seems to work.
The only way to bring in stuff from a database is with Scaffold-DbContext. However, that's an all or nothing affair. It's going to create entity classes for every table in the database (regardless of whether they already exist) and a DbContext to boot.
Either you're using code first and you create your entities and generate migrations that you run against the database OR you make changes to the database and then use the Scaffold-DbContext command to generate the context and all the associated entities. You cannot mix and match.
Long and short, you need to pick a strategy and stick with it. If you're more comfortable with the database then do everything there and scaffold the code from that. Otherwise, if you want to use code first, then make a commitment to that and never manually touch your database.

Cannot drop database. Because it is in currently use. EF Code first approach

I am using code first entity framework approach. I have changed the name Plane_EcoClass to Plane_Class property to the table in the database. It is showing with old property name in the db .How can I update the new property name?. Please let me know how to resolve this error.
public class Plane
{
[Key]
public int Plane_id { get; set; }
public string Plane_Name { get; set; }
public string Plane_No { get; set; }
public string Plane_Class { get; set; }
public virtual List<User>Users { get; set; }
}
you need to add a migration and update the database for the change to affect the database. In the package manager console, type something like:
add-migration YourMigrationName
to create the migration. Review the migration code. Be aware that Entity Framework may try to drop the previously named column and add a column for the new name. This can potentially cause data loss. If this is the case and not desired, then you can manually change the code to use the RenameColumn method.
After adding the migration, you can apply it to the database by going back to the package manager console and typing:
update-database
and then hitting enter. At this point, the package manager console will give you some output regarding running migrations and your seed method and then the database should reflect the updated column name

How to Add Extra Fields of FistName and LastName in Userprofile of Asp.Net MVC 4 Simple Membership?

I want to add 2 Extra fields in UserProfile Asp.Net Simple membership, But unable to add and not find any help from internet. Please give me some solutions.
Thanks in advance
To add fields to UserProfile in SimpleMembership (I will assume you want to use migrations and EF):
Ensure you have enabled migrations (use the Enable-Migration in the package manager console)
Edit the UserProfile class (assuming you are using, for example, the Visual Studio 2012 -> New Project -> ASP.NET MVC 4 Web Application -> Internet Application template, this will be created for you) to add your new properties (example below)
Add a migration which will update your database using the Add-Migration command.
Optionally edit the generated migration to handle default values and non-nullable fields.
Run that migration against your development database using the Update-Database command.
I have provided an overview about how SimpleMembership works, with UserProfile in this answer. Note that UserProfile can be moved from the UsersContext to the same DbContext as all your other classes, it does not have to be in a separate context.
SimpleMembership is designed to play well with code-first EF development, so that is the process I have outlined above. An example updated UserProfile class with a Forename, Surname and a LoginCount field would look like:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
[MaxLength(40)]
[Required]
public string Forename { get; set; }
[MaxLength(40)]
[Required]
public string Surname { get; set; }
[Required]
public int LoginCount { get; set; }
}
References:
ASP.NET MVC 4 Entity Framework Scaffolding and Migrations - task 3 shows how to enable migrations
MSDN: Code First Migrations - everything you need to know about migrations
StackOverflow: How do I use my own database with SimpleMembership and WebSecurity? What is MVC4 security all about?

How to edit a SQL Server XML data field with asp.net Dynamic Data

I have a site based around asp.net 3.5's Dynamic Data feature. Everything's working great, but I would like to add a tagging feature via a column with an XML data type. I've made the column and added an appropriate schema, but it is showing up as read-only and the scaffold will not display or modify the field.
So, I have a few questions:
What do I need to do in order to enable my scaffold to see this xml column?
How would I go about editing the tags through the scaffold without directly editing all the xml?
Would I add logic to the getter/setter in the metadata?
Presumably I would need a custom fieldTemplate, would I add the xml parsing to it?
I hope this is helpful. As you mention, you would have to create a field template for your XML data. :
[MetadataType(typeof(DocumentMetadata))]
[DisplayName("Documents")]
public partial class Document {
[ScaffoldColumn(true)]
[Display(Name = "Some Xml")]
public string SomeXml
{
get
{
return "<note><to>Joe</to><from>Mary</from><heading>Reminder</heading><body>Hello World</body></note>"
}
}
}
public class DocumentMetadata
{
[ScaffoldColumn(false)]
public object Id { get; set; }
[Display(Name="Type")]
public object DocumentType { get; set; }
[UIHint("CustomXmlFieldTemplate")]
[Display(Name="Some XML")]
public object SomeXml { get; set; }
}

Resources