Key Already Exists in Table when Scaffolding - c#

I am doing a code first example, and basically I have Products and Categories.
The Category Model is as follows :
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
and the Product model is as follows:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public int Stock { get; set; }
public string ImageName { get; set; }
//Category Navigation
public int CategoryId { get; set; }
public Category Category { get; set; }
}
When I try to create a Controller with the Web API 2 Controller with actions, using Entity Framework scaffold, I am getting an error :
There was an error running the selected code generator : 'Key already
exists in table'
I am suspecting its the Category Navigation part of the Product Model since without that code, the scaffold works.
What am I doing wrong? I tried to create it as a virtual property but I am still getting the same error.

You need to add the Model classes in your DbContext
public DbSet<Product> Products{ get; set; }
public DbSet<Category> Categories{ get; set; }
Now you could do the scaffolding.
This question will also help for a better understanding

Related

Entity Framework Code first migration creates incorrect tables and columns?

I am trying to migration a a C# model, and don't understand the tables and columns that EF6 end up creating.
This is the database models I want
and for that purpose have I defined these 3 c# models
public class Owner
{
[Required]
[Column("id")]
public int Id { get; set; }
[Required]
[Column("name")]
public string name { get; set; }
}
public class House
{
[Required]
[Column("id")]
public int Id { get; set; }
[Required]
[ForeignKey("owner")]
public Owner Owner { get; set; }
[ForeignKey("resident")]
public IEnumerable<Resident>? Resident { get; set; }
}
public class Resident
{
[Required]
[Column("id")]
public int Id { get; set; }
[Required]
[Column("renter_name")]
public string RenterName { get; set; }
}
This is what I end up getting when I do code first migration with EF:
I am confused on why House does not have a column Renter, which is nullable?
And why People has a column named People

Entity Framework error : Unable to determine the principal end of an association between the types

I'm using Entity Framework to build my database. My model contain two entities: Entite and ApplicationUser (see code below).
There are two relations between these entities:
One-to-Many: an Entite could contain one or many users. And a user belongs to one Entite.
One-to-One: an Entite must have one user as a responsible and a user can be responsible for only one Entite.
Entite:
public class Entite : AuditableEntity<int>
{
[Required]
[MaxLength(10)]
public String code { get; set; }
[Required]
[MaxLength(50)]
public String Libelle { get; set; }
[Required]
[MaxLength(10)]
public String type { get; set; }
[Key, ForeignKey("ResponsableId")]
public int? ResponsableId { get; set; }
public virtual ApplicationUser responsable { get; set; }
public int? RattachementEntiteId { get; set; }
[Key, ForeignKey("RattachementEntiteId")]
public virtual Entite rattachement { get; set; }
public List<Entite> Children { get; set; }
}
ApplicationUser:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Matricule { get; set; }
public DateTime? dateRecrutement { get; set; }
public int? entiteId { get; set; }
[ForeignKey("entiteId")]
public virtual Entite entite { get; set; }
}
When I tried to build the database using the Add-Migration command, I got this error :
Unable to determine the principal end of an association between the types
Any idea about this issue?
Thanks for your help
It looks like a small typo/error in your Entite model class.
The ForeignKey should be referencing your ApplicationUser, currently it is referencing itself, and a new Key will be generated for the responsable.
If we swap the ForeignKey reference to below, then this looks like it should solve your issue:
[Key, ForeignKey("responsable")]
public int? ResponsableId { get; set; }
public virtual ApplicationUser responsable { get; set; }
Or you can swap the reference like you have done on your rattachement.
public int? ResponsableId { get; set; }
[Key, ForeignKey("ResponsableId ")]
public virtual ApplicationUser responsable { get; set; }

Entity framework code first, shopping cart

I am new to entity framework, I was trying to implement a simple shopping cart using code first approach, and I didnt understand why entity generates the table in strange way below. Here is the cut down version of my classes:
Product.cs
public class Product
{
[Key]
public int ID { get; set; }
public int ProductCategoryID { get; set; }
public string ProductNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public string Color { get; set; }
public string Capacity { get; set; }
public string CapacityUnitMeasureCode { get; set; }
public decimal Price { get; set; }
public decimal Cost { get; set; }
public int Stock { get; set; }
}
ShoppingCart.cs
public class ShoppingCart
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
public int Quantity { get; set; }
public DateTime CreatedDate { get; set; }
public virtual List<Product> products { get; set; }
}
Because of this line
public virtual List products { get; set; }
Entity generates the Product table with 2 additional foreign keys:
ShoppingCart_ID & ShoppingCart_ProductID
Which I dont understand. my intention was to create a List of product that associated to a particular shopping cart. What I am I doing wrong. Could someone shed some light please!
SInce you have ProductID as one of the property in shopping cart class and you have virtual product collection in shopping cart, EF has established relationship between shopping cart and product class.
as suggested in comment you can remove product id class or you can create a view model class and establish relation ship between shopping cart and product class.
Sample View model can be
public class ShoppingCartProduct
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
}
you can read about view model here
http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAA&url=http%3A%2F%2Frachelappel.com%2Fuse-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications&ei=EP20VNqDHcTkuQTqvYGoAw&usg=AFQjCNHdOjOFhZGuBiLHZJ0wBGsG9qQtXw&sig2=rSFNWzWstWP0z0yRDhuXXQ
The great solution for you is to make a class ShopingCart wich contain all your products and their number:
[Table("Cart")]
public class ShopingCart
{
[Key]
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ICollection<ItemCart> Products { get; set; } // relationship one-to-many
}
And the class wich contains your ItemCart
[Table("ItemCart")]
public class ItemCart
{
[Key]
public int Id { get; set; }
public int Quantity { get; set; }
public virtual Product Product { get; set; } // relationship one-to-one
}
If you want to learn more look on this page: entity-tutorial
And try to make think simple: You have just 3 possible relationships:
one-to-one
one-to-many
many-to-many but here is creating an intermittent table link
Hope to be useful for you!

Entity Framework 1:0..1 relation in mvc 5

I wanted to create a relation between two of my models to be 1:0..1 but all i got is a 1..* relation:
public class MedicalExamination
{
public int Id { get; set; }
public DateTime EntryDate { get; set; }
public DateTime ExecutionDate { get; set; }
public DateTime AcceptanceDate { get; set; }
public string Description { get; set; }
public string State { get; set; }
public string Result { get; set; }
public string Comment { get; set; }
public virtual Visit Visit { get; set; }
[Required]
public virtual ExaminationDictionary ExaminationDictionary { get; set; }
}
and my second model:
public class ExaminationDictionary
{
[Key]
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public virtual MedicalExamination MedicalExamination { get; set; }
}
And after i ran it and updated the database i got a relation like this: http://scr.hu/11m6/4eny0
The thing is that i would like it to be 0..1:1 relation. Does anybody know a good solution for this ?
A 1-to-1 or 1-to-0or1 relation in Entity Framework is only possible if both tables share the same primary key.
So for example, your MedicalExamination is presumably the principal entity in the relationship. It has an Id column primary key. Your ExaminationDictionary table needs to have an Id column that is its primary.
You then describe the relationship using Fluent API like so:
modelBuilder.Entity<MedicalExamination>()
.HasOptional(m=>m.ExaminationDictionary)
.WithRequiredPrincipal(d=>d.MedicalExamination);

ASP.Net MVC with Entity Framework Code First Navigation Property

I have an entity called Service like following:
public class Service
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int serviceId { get; set; }
public string name { get; set; }
public string description { get; set; }
public ServiceCategory category { get; set; }
}
The category is chosen by the user through a drop down that holds the id and the name of the categories available in the db. the ViewModel will then return that id to me to save. The way I've been doing this so far is by going to my repository, getting the category object where the id matches the selected category in the view and then assigning it. This of course takes a round trip to the db.
I was wondering, since I already have the id, is there a better way of doing this where I don't go to the db?
modify your code to
public class Service
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int serviceId { get; set; }
public int ServiceCategoryId {get; set;} // Added
public string name { get; set; }
public string description { get; set; }
public ServiceCategory ServiceCategory { get; set; }
}
and fill ServiceCategoryId.

Categories

Resources