Update Azure mobile app Asp.Net backend database - asp.net

I have an Azure mobile app with an ASP.NET backend. I want to add a new column to an existing table. I have added the property and redeployed the service but this does not create the column in the table and gives me an error. I also tried to add the column manually with SQL management studio and kept the property in the DataObject class but this still errored. Please could you advise how I can add a new field to the mobile app database.
public class Petrol: EntityData
{
public int Mileage { get; set; }
public DateTime PurchaseDate { get; set; }
public float Quantity { get; set; }
public Decimal Cost { get; set; }
public string Station { get; set; }
public string Claim_Id { get; set; }
[ForeignKey("Claim_Id")]
public virtual Claim Claim { get; set; }
//This is the new column I would like to add
public string PhotoUrl { get; set; }
}
I have ran the Enable-Migrations command in Package Manager Console, but I am getting an error about the connection string.

The schema of your database is only deployed when your database is empty.
For a database already containing tables you have to implement code first migrations as described here: Implementing Table Controllers

Related

EF Core with cosmos issue

I have a SQL database that I'm using currently with EF Core. I have 2 objects:
public class Contact
{
public Guid ContactGUID { get; set; }
public string Name { get; set; }
[ForeignKey("CreatedBy")]
[InverseProperty(nameof(User.ContactCreatedBy))]
public virtual User CreatedByUser { get; set; }
...
}
public class User
{
public User
{
User = new HashSet<Contact>();
}
public Guid UserGUID { get; set; }
[InverseProperty(nameof(Contact.CreatedByUser))]
public virtual ICollection<Contact> ContactCreatedBy { get; set; }
...
}
This all works fine with EF Core connected to SQL. But something I would like to do is take this object that I've grabbed and save it to a separate CosmosDB database with EF Core.
When I try to do that however, I get the following error:
Microsoft.EntityFrameworkCore: When creating the relationship between
'User.ContactCreatedBy' and 'Contact.CreatedByUser' the entity type
'Contact' cannot be set as principal.
What is the best way to get past this error? I'd rather not create a whole separate object for my cosmos database that basically looks the same but w/out all the inverseproperties/etc. Is there a way to do that, or do I have to go about the long way?

Cannot generate Id using Data annotation (EF6)

I'm new at EF6 and Asp.net MVC5.
There's problem of generating a unique ID automatically when I try to create my entities using the code first approach.
Consider an entity like this:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PostId { get; set; }
[Required]
[MaxLength(100), MinLength(5)]
public string Title { get; set; }
public string Content { get; set; }
public string Thumbnail { get; set; }
public string Description { get; set; }
public DateTime DateCreated { get; set; }
When I put [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on PostId or even remove it. I was always get an exception error like this:
“Cannot insert the value NULL into column ‘PostId'”.
“column does not allow nulls. INSERT fails.
I don't know why EF6's always try to insert a null value to the Id column.
Then later, I found a solution.
I changed
DatabaseGeneratedOption.Identity to DatabaseGeneratedOption.None
and the problem was solved.
However, this solution doesn't seem to work like I expected.
the values inserted to the column are always the same. It's not unique.
With EF core, everything is just simple, I don't need DatabaseGenerated,just leave it to convention. But with EF6, I'm stuck. What I want is the Id field must be unique and increase everytime it inserted to the database.
Can someone please help me this?
I'm new to EF also, but I just create an Id field and it is inserted automatically by SQL Server, such as this model in my current project. The Id field populates as expected when I add new rows:
public class BlogPosts
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string ShortPost { get; set; }
[Required]
public string Post { get; set; }
[Required]
public string Tags { get; set; }
[Required]
public DateTime Updated { get; set; }
}
When you apply DatabaseGeneratedOption.Identity to your key property you are telling EF that the database will generate the identity. From the error it sounds like your database PostId column is not configured as an identity or primary key.
If you manually created the table and columns in the database you should ensure the configuration is at least compatible, or you should use migrations to ensure the database is configured in a good state for your EF model.

Circular Reference with Include in .NET Core

I am using code like below in .NET core
.Include(p => p.Company).ThenInclude(p => p.Country).ToList();
My classes look like below,
public partial class Company
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual Country Country { get; set; }
}
public partial class Country
{
public Country()
{
Companies = new HashSet<Company>();
}
public Guid Id { get; set; }
public string Name { get; set; }
public string ShortCode { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
And I want only Company and then Country in side the company to be populated. But I am getting the Company inside the Country and then Country in those Companies and so on populated which is causing the response delayed.
I have already tried difference examples of Include on Google/StackOverFlow.
This isn't actually a problem. EF has what's called "object fix-up". Internally, it uses an object cache. When it builds entity instances for database query results, it adds those to the object cache, allowing it to then pull out those objects later, rather than issuing the same queries again.
Because of this object cache, if it already existing entity instances corresponding to a relationship, it will auto-fill that relationship from the object cache. It's not issuing a series of circular queries forever.

ASP.Net MVC 5 when changing the class data annotations it gives exception error?

I created one Model class Employee
public class Employee
{
public int ID { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name Is Required") ]
public string Name { get; set; }
public int Email { get; set; }
public double Salary { get; set; }
public int Address { get; set; }
}
when I run the application it worked fine after that when I saw that field Address is Int so I
changed it to String or :
public class Employee
{
public int ID { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name Is Required") ]
public string Name { get; set; }
public string Email { get; set; }
public double Salary { get; set; }
public string Address { get; set; }
}
when I run the application it gives the following error:
An exception of type 'System.InvalidOperationException' occurred in ProductApps.dll but was not handled in user code
Additional information: The model backing the 'ProductContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
The reason you're experiencing this exception is because by making a change to the property type within your entity, Entity Framework needs to update the database to reflect your changes.
In this instance it needs to update the Email column within the Employee table to be of type int instead of string. And in order to force Entity Framework to do this you need to run the necessary console commands.
To run a console command go to Tools > Nuget Package Manager > Package Manager Console and run the following:
Add-Migration UpdatedEmailType followed by Update-Database. If you experience an error saying that migrations isn't enabled then you'll need to run the following command to enable the database migriations: Enable-Migrations.
Note:
Whilst Database Migrations can be a great help in creating a database schema, at times it can be hard work. If you're still experiencing issues then you can always disable migrations and update the database manually within SQL Server Management Studio or Visual Studio's database manager tool.

EF5 Code-First - Create new table

I'm working with asp.net mvc3 & Entity Framework5.
My database has been designed with the Code-First.
Entity Code
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
Create DB Option
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFDbContext>());
I use this option, the database has been created.
After the database has been created, I need a Role table was.
So I had to modify the code as follows.
Entity Code
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
I use Create DB Option again.
In this case, the existing Users table will be deleted after regeneration.
I would like to be added to the Role table, but leave data in the table Users.
What should I do?
Use Code-First Migrations.
Database.SetInitializer(null);
Then in Package Manager Console write:
add-migration addedRoles
If you did't enabled migrations before, You must enable it first:
enable-migrations
and last:
update-database
Complete guid:
http://msdn.microsoft.com/en-US/data/jj591621
Edit
If you want the database to be upgraded automatically whenever you run the application, you can use MigrateDatabaseToLatestVersion initializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFDbContext, Configuration>());
Learn how migrations work.
http://msdn.microsoft.com/en-us/data/jj591621.aspx
They have another initializer, MigrateDatabaseToLatestVersion. In contrast to the one you use, this one will automatically upgrade your database to latest version without recreating the whole database.

Resources