Error Entity Framework Database Changed - entity-framework

I have started with ASP.NET MVC and the Entity Framework recently.
With an existing Database, I tried to map my classes to the database tables. Without success.
Let me show you my database tables:
-> Categories
--> Id (PK)
--> Title
--> Description
-> Products
--> Id (PK)
--> Name
--> Description
--> Price
--> Category (FK -> CategoryTree)
-> CategoriyTree
--> Id (PK)
--> ParentCategory (FK -> Category)
--> ChildCategory (FK -> Category)
Now, my classes for the Entity Framework:
class Products
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal? Price { get; set; }
public virtual ICollection<CategoryTree> Category { get; set; }
}
class Categories
{
public int categoriesId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
class CategoryTree
{
public int Id { get; set; }
public virtual ICollection<Categories> ParentCategory { get; set; }
public virtual ICollection<Categories> ChildCategory { get; set; }
}
class EFDbContext : DbContext
{
public DbSet<Products> Products { get; set; }
public DbSet<Categories> Categories { get; set; }
public DbSet<CategoryTree> CategoryTree { get; set; }
}
If I start the application, the compiler alerts the following error message:
The model backing the 'EFDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I hope someone can help me to understand this ;-)
Best regards

In the Application_Start() method of your Global.asax.cs, add the following line:
Database.SetInitializer<EFDbContext>(null);
That will stop Entity Framework from checking for changes to your model since the creation of your database.

For an existing database, I would suggest use EF power tool to reverse engineering to generate POCO classes.

The only difference I can see from the above information id Categories.Id in the db and Categories.categoriesId in the model (assuming no typo).
Also check the nullability of columns, for example Product.Price is nullable in the model, is it so in the db?
Can I also suggest, generate a new db with a different name from your model and compare to the existing db. The db name is specified in the connection string, so add a constructor to you DbContext class and pass the connection string in,
internal class EFDbContext : DbContext
{
public EFDbContext(string connectionString) : base(connectionString)
{
}

Related

Invalid column name 'Genre_Id1'. In Entity FrameWork

I am newbie to Entity Framework Code First approach.
I was created the following Genre model:
public class Genre
{
public byte Id { get; set; }
public string Name { get; set; }
}
then add migration and update database.
After that I create The following Movie Model
public class Movie
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
public int NumberInstock { get; set; }
public Genre Genre { get; set; }
}
then add migration and update the database which generate a 'Genre_Id' column as a foreign key.
I try to add the following property to the MovieModel
public byte Genre_Id { get; set; }
but when I run the application I got the error Invalid column name 'Genre_Id1'.
I don't have a column name like this.
The solution is when I added a Genre navigation property to MovieModel I should add GenreId property also the add migration and update-database. That means add the navigation property and the property together then add migration and update database

Entity Framework one to many : SqlException

I have a little problem when I try to save an item in my DB using EntityFramework.
My classes looks like:
public partial class Site
{
public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
public string Adress { get; set; }
public City City { get; set; }
public Country Country { get; set; }
public string VATNumber { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string Name { get; set; }
public string IsoCode { get; set; }
}
And when I try to create a new site in my controller it works, but when I try to add a link to an existing Country :
if (SiteProvider.GetSiteByName(Site.Name) == null)
{
Site.Country = CountryProvider.GetCountryById(1);//it's working, i see the link to the right country
SiteProvider.Create(Site);
}
public static void Create(Site Site)
{
using (MyDBContext Context = new MyDBContext())
{
Context.Site.Add(Site);
Context.SaveChanges(); //here is the problem
}
}
I got this error:
SqlException: Cannot insert explicit value for identity column in
table 'Country' when IDENTITY_INSERT is set to OFF
Thanks in advance for your help.
Add CountryId property to Site class and when adding a new Site set CountryId instead of Country property
public int CountryId { get; set; }
[ForeignKey("CountryId")]
public Country Country{ get; set; }
You have a slight issue with your use of contexts here. You have used one DBContext instance to load the country (where this country object will be tracked) and then a second DBContext to save the site (where the first country object is a property).
It is preferable to perform all your operations for a single unit of work by using one DB context (that would be shared between your classes) and the responsibility for disposing of it to be handled outside your repository layer.

Entity Framework : Code First Approach. Creating Entities using TPT inheritance

I am new to entity framework and I am using code first approach to create entities using TPT inheritance.
My requirement is to create the entities as per the attached diagram where ID is PK for Customers table and FK for the AddressDetails and ContactDetails table. Based on the keys I also need to create the association and navigation properties for the entities. Table Diagram
In my code I have created entities as
public class Customer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int ZipCode { get; set; }
public virtual ContactDetails ContactDetails { get; set; }
public virtual AddressDetails AddressDetails { get; set; }
}
[Table("ContactDetails")]
public class ContactDetails: Customer
{
public string MobileNo { get; set; }
public string EmailId { get; set; }
}
[Table("AddressDetails")]
public class AddressDetails: Customer
{
public string BillingAddress { get; set; }
public string DeliveryAddress { get; set; }
}
My question is, have I created the association and navigation properties correctly or do I need to add them in the ContactDetails and AddressDetails class as well? Also, when I run the code the entities are getting created in the database but for the Customer table there are 2 additional columns created as AddressDetails_Id(FK,int,null) and ContactDetails_Id(FK,int,null). I think they are created because of the navigation property but I do not need these columns in the database to be created. Also the values are always null in these two columns.
Any help would be appreciated. Thanks in advance.

Database Generated by EF5 Not Creating Join Table When There are Multiple Relationships

I have a User and an Organization class. They look like this
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Organization> Organizations { get; set; }
}
public class Organization : EntityBase
{
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
And both inherit from an EntityBase class to get common fields like Id and created/updated tracking.
public abstract class EntityBase
{
public int Id { get; set; }
public DateTime Created { get; set; }
public virtual User CreatedBy { get; set; }
public DateTime Updated { get; set; }
public virtual User UpdatedBy { get; set; }
}
As denoted by the ICollection properties on both, there should be a many-to-many relation. However when my database is autogenerated I get incorrect foreign keys added to my tables
If I change the CreatedBy and UpdatedBy to be strings instead of User properties I get a join table, which is what I was looking for.
Is this a matter of Entity Framework simply being confused and I need to supply many-to-many configuration in the using fluent mappings, or have I done something wrong?
If you have multiple relationships you need to configure them manually by fluent API or using attributes,
Note:If you have multiple relationships between the same types (for
example, suppose you define the Person and Book classes, where the
Person class contains the ReviewedBooks and AuthoredBooks navigation
properties and the Book class contains the Author and Reviewer
navigation properties) you need to manually configure the
relationships by using Data Annotations or the fluent API
Here is the article from Microsoft.

How Do I Resolve "A specified Include path is not valid"?

I have a parent-child relationship setup that is fairly basic. The end result is that I want to be able to return the resulting tables as JSON through ASP.NET MVC WebAPI. I am using Entity Framework 5.0 beta 2.
I can demonstrate the error I'm running into with a simple example. Given the classes Category and Product with the corresponding data context:
public class Category
{
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual IEnumerable<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Title { get; set; }
public virtual Category Category { get; set; }
public virtual int CategoryId { get; set; }
}
public class ProductDataContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
When I try to run a query that includes the products I get the following error:
A specified Include path is not valid. The EntityType 'FooAndBar.Category'
does not declare a navigation property with the name 'Products'.
The statement to fetch is pretty straightforward:
var everything = dc.Categories
.Include(c => c.Products);
What is the correct way to setup the columns and/or the query so that the Products are included with the Categories?
Child collection properties must be declared as anICollection<T>, not anIEnumerable<T>.
Also, you do not need to explicitly add a CategoryId field to the child class; EF will create that automatically in the database.